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

代码是:

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

                }

最佳答案

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

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

07-24 20:59