Replacing a single character in a String

后端 未结 3 767
广开言路
广开言路 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: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.

提交回复
热议问题