private String theLetters = "_ _ _ _ _\n";
StringBuilder myName = new StringBuilder(theLetters);
for(char e : theSecretWord.toLowerCase().toCharArray())
{
if(e == theUsersGuess.charAt(0))
{
int index = theSecretWord.indexOf(e) * 2;
myName.setCharAt(index, theUsersGuess.charAt(0));
theLetters = myName.toString();
}
}
For some reason this will only replace the first occurrence of a letter from the String theSecretWord and not the second, even though this for each loop goes through each character and replaces it in theLetters accordingly. I don't understand why it won't replace more than one occurrence of a letter.
I think it's because the loop stops once it finds a matching letter even though it shouldn't.
private String replaceOccurrence(String text, String replaceFrom, String replaceTo, int occurrenceIndex)
{
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(replaceFrom);
Matcher m = p.matcher(text);
int count = 0;
while (m.find())
{
if (count++ == occurrenceIndex - 1)
{
m.appendReplacement(sb, replaceTo);
}
}
m.appendTail(sb);
return sb.toString();
}
For example if you want to replace the second occurrence of "_" with "A", then:
String theLetters = "_ _ _ _ _\n";
String replacedText = replaceOccurrence(theLetters, "_", "A", 2);
Result: _ A _ _ _
Another Way is
String string1= "Hello";
int first=string1.indexOf('l');
String newstr= string1.substring(0, first+1);
String newstr2= string1.substring(first+1, string1.length()).replaceFirst("l", "k");
System.out.println(newstr+newstr2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With