Replacing a single character in a String

后端 未结 3 764
广开言路
广开言路 2021-01-23 14:03

The issue is needing to replace a single character in a given string while maintaining the other characters in the string.

The code is:

    i         


        
相关标签:
3条回答
  • 2021-01-23 14:27

    You almost did it, just add a counter in your loop:

    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);
    
    0 讨论(0)
  • 2021-01-23 14:31

    You can use command.replaceAll("and", "a") for example

    0 讨论(0)
  • 2021-01-23 14:36

    You can use StringBuilder to replace a single character at some index, like this:

    int charIndex = baseString.indexOf(charToBeReplaced);
    StringBuilder baseStringBuilder = new StringBuilder(baseString);
    baseStringBuilder.setCharAt(num2replace, secondChar);
    

    Read more about StringBuilder's setCharAt() method here.

    0 讨论(0)
提交回复
热议问题