Guessing symbols in a Sting word java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Got a String like:
String str = "###############";
Got guess word, for example:
String guess = "Java"
User must guess word:
User input:
Sava
Sring should be:
String str = "#a#a###########";
all right symbols placed on their indexes
String is immutable class.
I chose Stringbuilder
for (int i = 0; i < length ; i++) {
if (rnd.charAt(i) == guess.charAt(i) && rnd.charAt(i) != '#'){
sb.append(rnd.charAt(i));
}
}
System.out.println(sb);
sb.delete(0, sb.length());
Stringbuilder add right symbols not on possition 'i', but on the last indexes.
Example:
guess word: Java
user input Sala:
System.out.println(sb);
###############aa
How I can achieve needed result?
And what tools should I use?
needed result:
Example:
guess word Java:
user input Sala:
System.out.println(sb);
#a#a###########

Work like this:
private static String word(){
String guess = new Scanner(System.in).nextLine();
return guess;
}
private static void guessWord(String[]arr) {
int random = new Random().nextInt(arr.length);
String rnd = arr[random];
int length = 15;
StringBuilder sb = new StringBuilder();
String guess = "";
int rndLength = length - rnd.length();
int guessLength = length - guess.length();
do {
System.out.println("Enter a word: ");
guess = word();
if (sb.length() < length){
for (int i = 0; i < length ; i++) {
sb.append("#");
}
}
for (int i = 0; i < length && i < rnd.length() && i < guess.length(); i++) {
if (rnd.charAt(i) == guess.charAt(i)){
sb.setCharAt(i, rnd.charAt(i));
sb.delete(length, sb.length());
}
}
if (rnd.equals(guess)){
System.out.println("Guess word: " + rnd);
break;
}else if (!rnd.equals(guess)) {
System.out.println(sb);
}
}while (!rnd.equals(guess));
}

You can do it as follows:
public class Main {
public static void main(String[] args) {
String str = "#a#a###########";
String guess = "Java";
String input = "Sala";
StringBuilder sb = new StringBuilder();
int i;
for (i = 0; i < str.length() && i < guess.length() && i < input.length(); i++) {
// In case of a match, append the matched character
if (guess.charAt(i) == input.charAt(i)) {
sb.append(guess.charAt(i));
} else {// Else append the placeholder symbol from `str`
sb.append(str.charAt(i));
}
}
// Append the remaining placeholder characters from `str`
sb.append(str.substring(i));
// Display
System.out.println(sb);
}
}
Output:
#a#a###########

Related

How to count number of character Occurrences inside a string and replace selected character with the counts [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 20 days ago.
Improve this question
My task is to find number of occurrences of a string character and replace the character with the number of occurrence up to that particular index inside the string
public static void main(String[] args) {
char[] arr = "hello".toCharArray();
arr[2] = '1';
arr[3] = '2';
System.out.println(arr);
}
Output should be: he12o
I know we cant reuse this approach.
what is the output of "helololol"?
output for helololol, ch='l' , then the output should be he1o2o3o4; if ch='o' then output should be hel1l2l3l
If according to this rule, Can be achieved with a loop:
public static void main(String[] args) {
char flag = 'l';
String str = "hellollololollol";
int num = 1;
for(int i = 0, len = str.length(); i < len; i++) {
if (str.charAt(i) == flag) {
str = str.substring(0, i) + num++ + str.substring(i + 1);
}
}
System.out.println(str);
}
Note that if the number of specified characters exceeds 9, it will look weird, If the number of characters exceeds 9, special processing is required:
public static void main(String[] args) {
char flag = 'l';
String str = "hellollololollollol";
int num = 1;
for(int i = 0, len = str.length(); i < len; i++) {
if (str.charAt(i) == flag) {
str = str.substring(0, i) + num++ + str.substring(i + 1);
if (num > 10) {
len++;
}
}
System.out.println(str);
}
}
The same problem, if the number of characters exceeds 100, 1000, 10000, special processing is required, because the length of the number added to the string is one bit longer than the original character, how to deal with it flexibly, you need to think about it yourself!
Instead of using primitive methods to manipulate string , we can use the following to have clean code .
public static void main(String args[]) {
String str="helolololololololololololololololololololololololololololololololololololo";
String checkString="l";
int count=1;
StringBuilder sb=new StringBuilder();
List<String> strLst= new ArrayList<String>();
for(int i=0;i<str.length();i++) {
strLst.add(String.valueOf(str.charAt(i)));
}
for(String x : strLst) {
if(x.equals(checkString)) {
sb.append(count);
count++;
}else {
sb.append(x);
}
}
System.out.println(sb);
}
The output for the above string will be
he1o2o3o4o5o6o7o8o9o10o11o12o13o14o15o16o17o18o19o20o21o22o23o24o25o26o27o28o29o30o31o32o33o34o35o36o
With this implementation , we don't have to worry about splitting the string using substring and checking their index .Will work for 'n' number of repetitive letters.

How to find most common used number in users input? Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How could an user input their numbers, for example : "122113333443" and I needed to output "3333".
If they again input something like "1224" I then needed to output "22".
How would this be possible if I don't know which numbers they are going to input and how the code would look like?
So far I only have the beginning, which shows input output error if the input aren't numbers.
int k;
Scanner sc = new Scanner(System.in);
System.out.println("input string:");
if (sc.hasNextInt())
k = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
You can use a variable (StringBuilder longest in the code given below) to keep track of the longest sequence of characters having the same characters.
Iterate all characters of the string and keep appending the characters to a StringBuilder (StringBuilder sb in the code given below) until a different character is found. When this happens, reset the sb.
After each append to the sb, check if its length has become bigger than that of longest. If yes, transfer the content of the StringBuilder to longest.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input string: ");
String input = sc.nextLine();
System.out.println(getLongest(input));
}
static String getLongest(String str) {
StringBuilder sb = new StringBuilder();
StringBuilder longest = new StringBuilder();
char current = 0;
// Process all but the last character of str
for (int i = 0; i < str.length() - 1; i++) {
current = str.charAt(i);
sb.append(current);
if (sb.length() > longest.length()) {
longest = new StringBuilder(sb);
}
if (current != str.charAt(i + 1)) {
sb = new StringBuilder();
}
}
// Process the last character of str
sb.append(str.charAt(str.length() - 1));
if (sb.length() > longest.length()) {
longest = new StringBuilder(sb);
}
return longest.toString();
}
}
A sample run:
Input string: 122113333443
3333
Another sample run:
Input string: 1224
22
This is Java not JavaScript, wrong tag. However, heres my shot. I am not that good with java but anyway:
public String findMostCommon(int inp) {
int[] occuranceTable = new int[9];
for (int i = 0; i < occuranceTable.length; i++) {
occuranceTable[i] = 0;
}
// Convert input int to Array of digits
String temp = Integer.toString(inp);
int[] digits = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
digits[i] = temp.charAt(i) - '0';
}
// Get Occurances of each digit
for(int digit : digits) {
occuranceTable[digit]++;
}
// Find most frequent digit
int max = -1;
for (int i = 0; i < occuranceTable.length; i++) {
max = occuranceTable[i] > max ? i : max;
}
// Make result string
String result = "";
for (int i = 0; i < occuranceTable[max]; i++)
result += String.valueOf(max);
return result;
}

Pallindrome String is replaced by * character [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Input a string which contains some palindrome substrings. Find out the position of palindrome substrings if exist and replace it by *. (For example if input string is “bob has a radar plane” then it should convert in “** has a ***** plane”.
My code is given below.
import java.util.Scanner;
public class Pallindrome_String {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String sen;
System.out.println("Enter the String: ");
sen = in.nextLine();
pallindrome(sen);
in.close();
}
public static void pallindrome(String s) {
int len = s.length();
for (int i = 0; i < len; i++) {
String res = "";
if (s.charAt(i) == ' ') {
res = s.substring(0, i);
String rev = "";
for (int j = res.length() - 1; j >= 0; j--) {
rev = rev + res.charAt(i);
}
if (rev.equals(res)) {
rev = "*";
System.out.print(rev + " ");
} else {
System.out.print(res + " ");
}
}
}
}
}
There is a simpler, more efficient way of finding palindromes in Java. I'll explain the steps to implementing it.
first, after getting your input 'sen', you can use the split method of the String class to seperate each word.
sen = in.nextLine();
String[] splitted = s.split(" "); // seperates the string when there is a whitespace and stores the resulting words in an array
After you've got the words in an array, you can check each word and see if its a palindrome. To do so, you can read the word front to back and back to front and compare the result.
If u find a palindrome, store its index (position in the 'splitted' array). After you've gone through all the words in the 'splitted' array, you can then print out the appropriate number of *'s based on the length of the word.
The split() will loose double spaces and punctuation in source string and make a lot of useless objects in memory. This is more correct solution. IMHO
public static void main(String[] args) {
String s = "Bob! Do you have a radar plane?";
StringBuilder sb = new StringBuilder(s);
Matcher m = Pattern.compile("[a-zA-Z]+").matcher(s);
while (m.find()) {
String word = m.group();
if (word.length() == 0)
continue;
String reversed = new StringBuffer(word).reverse().toString();
if (word.equalsIgnoreCase(reversed)) {
StringBuilder replacement = new StringBuilder();
for (int i = 0; i < word.length(); i++)
replacement.append('*');
sb.replace(m.start(), m.end(), replacement.toString());
}
}
System.out.println(sb);
}

Check if a string has all the characters of another string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
String one = "This is a test";
String two = "This is a simple test";
I want to check if two contains all the characters that are in one, and ignore the fact it has extra characters.
The fastest thing would probably be to break them up to HashSets and then apply containsAll
public static Set<Character> stringToCharacterSet(String s) {
Set<Character> set = new HashSet<>();
for (char c : s.toCharArray()) {
set.add(c);
}
return set;
}
public static boolean containsAllChars
(String container, String containee) {
return stringToCharacterSet(container).containsAll
(stringToCharacterSet(containee));
}
public static void main(String[] args) {
String one = "This is a test";
String two = "This is a simple test";
System.out.println (containsAllChars(one, two));
}
static boolean stringContains(String longer, String shorter) {
int i = 0;
for (char c : shorter.toCharArray()) {
i = longer.indexOf(c, i) + 1;
if (i <= 0) { return false; }
}
return true;
}
Using a simple loop over the set of the characters in the first string:
String s1 = "This is a test";
String s2 = "This is a simple test";
Set<Character> chars = new HashSet<Character>();
for(int i = 0; i < s1.length(); i++) {
chars.add(s1.charAt(i));
}
for (Iterator<Character> iterator = chars.iterator(); iterator.hasNext();) {
Character character = iterator.next();
if(!s2.contains(character.toString())) {
// break and mark as not contained
break;
}
}
If words are meant to be checked, then you could split the string around whitespaces into a list of words:
String[] words1 = s1.split("\\s");
String[] words2 = s2.split("\\s");
List<String> wordList1 = Arrays.asList(words1);
List<String> wordList2 = Arrays.asList(words2);
System.out.println(wordList2.containsAll(wordList1));
two.startsWith(one)
If you aren't sure about the start position (the above assumes 0), try using the following API
startsWith(String, offset)
Try this. I know it's long but it works
public static void main(String[] args)
{
String String1,String2;
int i, j, count1, count2;
count1 = 0;
count2 = 0;
String1 = "This is a test";
String2 = "This is a simple test";
char[] list1 = new char[String2.length()];
char[] list2 = new char[String2.length()];
char[] list3 = new char[String2.length()];
for (i = 0; i <= String1.length() - 1; i++)
{
list1[i] = String1.charAt(i);
for (j = 0; j <= String2.length() - 1; j++)
{
list2[j] = String2.charAt(j);
if (list1[i] == list2[j])
{
i++;
count1++;
}
}
}
for (i = 0; i <= String1.length() - 1; i++)
{
list1[i] = String1.charAt(i);
for (j = 0; j <= String1.length() - 1; j++)
{
list3[j] = String1.charAt(j);
if (list1[i] == list3[j])
{
i++;
count2++;
}
}
}
if (count1 >= count2)
System.out.println(true);
else
System.out.println(false);
}

Printing characters from a string occurring in another string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want characters from a string occurring in another string to be printed; characters which don't occur replaced by an asterisk.
For example:
string 1: helloworld
string 2: hord
Output should be:
h***o**r*d
Only characters from string 2 which occur in string 1 ar printed; characters from string 1 which don't occur in string 2 are represented as an asterisk.
I have written the following code:
public class ProgramonStrings {
public static void main(String[] args) {
{
String str1 = "helloworld";
String str2 = "hord";
StringBuffer sbf = new StringBuffer();
StringBuffer sbf2 = new StringBuffer();
String output;
for (int i = 0; i < str1.length(); i++) {
int count = 0;
for (int j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
sbf.append(str1.charAt(i));
count++;
}
}
if (count == 0) {
sbf.append('*');
}
}
output = sbf.toString();
for (int i = 0; i < output.length(); i++) {
int count = 0;
if (output.charAt(i) != '*') {
for (int j = i + 1; j < output.length(); j++) {
if (output.charAt(j) == output.charAt(i)) {
//output.replace(output.charAt(j), '*');
sbf2.append('*');
count++;
}
}
}
if (count == 0) {
sbf2.append(output.charAt(i));
}
}
System.out.println(sbf2);
System.out.println(sbf2);
}
}
Since then I am getting output as:h*****or*d
So can anyone correct my program to get the appropriate output i.e.,:h***o**r*d
You only need to iterate once over the text string. Iterate over it and compare the current character in the string with the next character in the second string. If it's equal, then consume the character from the second string, that is, increment the pointer. Else print an asterisk character (*).
If pointer < str2.length() is not true, that means that all characters from the second string are consumed.
public static void main(String[] args) {
String str1 = "helloworld";
String str2 = "hord";
int pointer = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str1.length(); i++) {
if (pointer < str2.length() && str1.charAt(i) == str2.charAt(pointer)) {
sb.append(str1.charAt(i));
pointer++;
}
else {
sb.append('*');
}
}
System.out.println(sb.toString());
}
Notice that it is better to use StringBuilder instead of StringBuffer.
You can use the code similar to this which gives the required output
public class ProgramOnStrings {
public static void main(String[] args) {
// TODO Auto-generated method stub
Compare cobj=new Compare();
cobj.compareStrings();
}
}
class Compare
{
String s1="helloworld";
String s2="hord";
int array[];
String small,big;
Compare()
{
if(s1.length()<s2.length())
{
small=s1;
big=s2;
array=new int[small.length()];
}
else
{
small=s2;
big=s1;
array=new int[s2.length()];
}
System.out.println("small\t"+small+"\tbig\t"+big);
}
public void compareStrings()
{
int j=0;
for(int i=0;i<big.length();i++)
{
if(small.charAt(j)==big.charAt(i))
{
array[j]=i;
System.out.println("if: The selected positions are"+i);
j++;
}
}
int m=0;
for(int k=0;k<big.length();k++)
{
if(array[m]==k)
{
System.out.print(small.charAt(m));
m++;
}
else
{
System.out.print("*");
}
}
}
}

Categories

Resources