How to set a specific location in a string in Java?

I have a string called str

str = "hi john";

Now I want to set J char to g. how can I do this?

Solution

You cannot modify a string directly, but you can use StringBuilder:

str = "hi john";
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(3,'g');
str = sb.toString();

.. Or convert it to char [] and return

str = "hi john";
char[] chars = str.tocharArray();
chars[3] = 'g';
str = new String(chars);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>