簡體   English   中英

如何替換字符串中char的第二次出現? (Java)

[英]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();
    }
}

出於某種原因,這只會替換字符串theSecretWord中第一次出現的字母,而不會替換第二次出現的字母,即使每個循環都經過每個字符並相應地將它們替換為字母也是如此。 我不明白為什么它不能代替一個字母出現多次。

我認為這是因為一旦找到匹配的字母,循環就停止了,即使它沒有找到。

我認為這是您正在尋找的代碼,

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

另一種方式是

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

通過使用StringBuilder,您可以通過以下代碼來實現

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

例如,如果要將“ _”的第二次出現替換為“ A”,則:

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

結果:_ A _ _ _

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM