简体   繁体   中英

How to replace second occurence of char in a String? (Java)

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.

I think this is the code you're looking for,

 String word, letter;
        word = "test";
        letter = "t";
        int i = 0;

        i = word.indexOf(letter);

        while (i > -1) {
            // store i in arrayList
            i = word.indexOf(letter, i + 1);}

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);

By using StringBuilder you can achieve this by using below code

    String string1= "Hello";
    int first=string1.indexOf('l',string1.indexOf('l')+1);
    StringBuilder SB = new StringBuilder(string1); 
    SB.setCharAt(first, 'k'); 
    System.out.println(SB);
private String replaceOccurance(String text, String replaceFrom, String replaceTo, int occuranceIndex)
{
    StringBuffer sb = new StringBuffer();
    Pattern p = Pattern.compile(replaceFrom);
    Matcher m = p.matcher(text);
    int count = 0;
    while (m.find())
    {
        if (count++ == occuranceIndex - 1)
        {
            m.appendReplacement(sb, replaceTo);
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

For example if you want to replace the second occurance of "_" with "A", then:

String theLetters = "_ _ _ _ _\n";
String replacedText = replaceOccurance(theLetters, "_", "A", 2);

Result: _ A _ _ _

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM