2017-02-14 175 views
-3

我正在嘗試使用方法來替換字符串中其他字符的某些字符,但它似乎不起作用。替換字符串中的字符Java

public String replaceLetter(String word, char letterToReplace, char replacingLetter) 
{ 
    String word2 = word.replaceAll("letterToReplace", "replacingLetter"); 
    return word2;  
} 
+0

['word.replace(letterToReplace,replacedLetter)'](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-char-char-)。 –

+0

閱讀您使用的方法和類的javadoc是理解錯誤原因的方法,以及您可以使用的其他方法。 –

回答

-1
public String replaceLetter(String word, String letterToReplace, String replacingLetter) 
{ 
    String word2 = word.replaceAll(letterToReplace, replacingLetter); 
    return word2;  
} 

,或者,如果你需要傳遞char的方法

public String replaceLetter(String word, char charToReplace, char replacingChar) 
{ 
    String letterToReplace = String.valueOf(charToReplace); 
    String replacingLetter = String.valueOf(replacingChar); 
    String word2 = word.replaceAll(letterToReplace, replacingLetter); 
    return word2;  
} 
+0

用''。''作爲'letterToReplace'來試試。 –

0

String.replace應該做你描述的到底是什麼。

System.out.println("foo".replace('f', 'b')); 

會打印:

你的情況
boo 

所以:

public String replaceLetter(String word, char letterToReplace, char replacingLetter) 
{ 
    String word2 = word.replace(letterToReplace, replacingLetter); 
    return word2;  
} 

即使你可以只使用.replace(char, char)如上所述。