【问题标题】:Replace characters in string Java替换字符串Java中的字符
【发布时间】:2017-02-14 16:38:56
【问题描述】:

我正在尝试使用一种方法通过参数将某些字符替换为字符串中的其他字符,但它似乎不起作用。

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

【问题讨论】:

标签: java string character


【解决方案1】:

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)

【讨论】:

    【解决方案2】:
    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;    
    }
    

    【讨论】:

    • 试试这个'.'作为letterToReplace
    猜你喜欢
    • 2015-12-23
    • 2013-07-09
    • 2021-01-27
    • 2012-06-27
    • 2015-05-01
    • 1970-01-01
    • 2023-03-25
    • 2015-05-02
    • 1970-01-01
    相关资源
    最近更新 更多