替换String中的单个字符

时间:2017-03-03 03:45:28

标签: java

问题是需要替换给定字符串中的单个字符,同时保留字符串中的其他字符。

代码是:

    if(command.equalsIgnoreCase("replace single"))
    {
        System.out.println("Enter the character to replace");
        String char2replace = keyboard.nextLine();
        System.out.println("Enter the new character");
        String secondChar = keyboard.nextLine();    
        System.out.println("Which " + char2replace + " would you like to replace?");
        int num2replace = keyboard.nextInt();

            for(int i=0; i< bLength; i++)
            {   

                if(baseString.charAt(i)== char2replace.charAt(0))
                {
                    baseString = baseString.substring(0, i) +
                            secondChar + baseString.substring(i + 1);

                }

3 个答案:

答案 0 :(得分:1)

你几乎做到了,只需在循环中添加一个计数器:

int num2replace = keyboard.nextInt();
int count = 0;
for (int i = 0; i < bLength; i++) {
    if (baseString.charAt(i) == char2replace.charAt(0)) {
        count++;
        if (count == num2replace){
            baseString = baseString.substring(0, i) +
                    secondChar + baseString.substring(i + 1);
            break;
        }
    }
    if (char2replace.length() > 1) {//you need move this out of loop
        System.out.println("Error you can only enter one character");
    }


}
System.out.println(baseString);

答案 1 :(得分:1)

您可以使用command.replaceAll("and", "a")例如

答案 2 :(得分:0)

您可以使用StringBuilder替换某个索引处的单个字符,如下所示:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

阅读有关StringBuilder的setCharAt()方法here的更多信息。