0
Java Question
In Python I used this method for the basis of my Hangman game letters=["A","B","C"] word="CAT" blanks="-"*len(word) for i in range(len(word)): if word[i] in letters: blanks=blanks[:i] + word[i] + blanks[i+1:] If the letter in word is in the list of guessed letters, it rebuilds the word blanks, inserting The letters where they belong. My question is how can I rebuild a string in this manner using Java?
2 Answers
+ 2
I am a nooby at Python so hopefully I'm on the right track with what you want here, but..:
You can use a StringBuilder to remove characters. It's a mutable String.
It may look something like this:
StringBuilder word = new StringBuilder("kitty");
// example stuff
char guess = 'k';
int index;
while((index = word.indexOf(guess)) != -1)
{// gets all repeated letters
// add guess to blanks
blanks[index] = guess;
word.deleteCharAt(index);
// remove guess from word
}
Or, use substring on a string to create a new string that does not include the removed character you wanted.
Or a for loop like this:
String word = "kitty";
char guess = 'k';
String newString = "";
for(int i = 0; i < word.length(); i++)
if(guess != word.charAt(i))
newString += word.charAt(i);
+ 1
Awesome! Your final example should work perfectly... Thank You! That is exactly what I wasn't finding on Google. I was probably wording it poorly lol



