开发者

str.setCharAt(index,'X')

开发者 https://www.devze.com 2023-02-02 15:34 出处:网络
Is开发者_如何转开发 there a way to use str.charAt(index) to replace a specific char by index?

Is开发者_如何转开发 there a way to use str.charAt(index) to replace a specific char by index? Something like this:

str.setCharAt(1,'X'); // replace 2nd char with 'X'

Is there any easy way to do that?


Depending on the source of str you may be able to do something like this:

StringBuilder str = new StringBuilder("Test string");
str.setCharAt(1, 'X');
str.toString();

If you have a string that you are piecing together and modifying a lot, it makes more sense to use a StringBuilder instead of a string. However, if you are modifying a String from another method call, the other answers may be more appropriate.


StringBuilder has a setCharAt() method (thanks @John for identifying that you should use it over StringBuffer):

StringBuilder sb = new StringBuilder(str);
sb.setCharAt(1, 'X');
str = sb.toString();

Or you can use substring(), which is a little messy and less efficient:

str = str.substring(0, 1) + 'X' + str.substring(2);

Strings are immutable (well, sort of), so you have to create a new string and assign it to str.


Not sure if this is more or less efficient than the other proposed solutions (though it seems simpler):

char[] chars = str.toCharArray();
chars[1] = 'X';
str = new String(chars);

This is the same approach suggested in a related question.


You can split the string at the index, insert the character and then concatenate the remaining part of the string:

public static String replaceCharAt(String s, int pos, char c)
{
    return s.substring(0, pos) + c + s.substring(pos + 1);
}

Where s is the input string.


Use the StringBuilder class (not StringBuffer), it has a replace method looking like sb.replace(0, 1, "X"); or if it's always just a char use sb.setCharAt(0, 'X'); and is very useful anyway when you want to mutate strings.

0

精彩评论

暂无评论...
验证码 换一张
取 消