0
How to hide string with stars?
i have to prompt the user for a word and then print the word with stars. I know the process of asking the user for the word. Im not sure how to replace the characters with star. I know theres the .replaceAll method but I dont want to use that
5 Respuestas
+ 1
I think that to use char array instead of String[] could simplify @VEdward's code.
An char array can be easily assembled into String without writing a for loop.
Scanner inp = new Scanner(System.in);
String inStr = inp.next();
char[] inWordChars = inStr.toCharArray();
for (int i = 0; i < inWordChars.length; i++) {
inWordChars[i] = '*';
}
String outputStr = new String(inWordChars);
System.out.println(outputStr);
0
Which do you want to hide, entire word or only specific characters?
0
entire word
0
ok, concatenate stars for [word length] times by for loop.
instant example:
public static String hide(String word) {
String stars = "";
for (int i = 0; i < word.length(); i++) {
stars += '*';
}
return stars;
}
0
Scanner inp = new Scanner(System.in);
String inStr = inp.next(); //the word input by user
//create array of size same as length of word
String[] inWordChars = new String[inStr.length()];
//now split the string it will give array
inWordChars = inStr.split("");
//replace all(or the ones you want) with stars
for(int i=0; i<inWordChars.length;i++){
//replace each character to star
inWordChars[i] = "*";
}
//now we will join all characters
//create a blank string
String outputStr = "";
//add all members to string using for loop
for(int j=0; j<inWordChars.length;j++){
outputStr += inWordChars[j];
}
//at last print it to screen
System.out.print(outputStr);