Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a specific positon in a String in Java?

Tags:

java

string

I have a String with name str.

str = "hi john";

Now I want to set j char to g. How can I do that?

like image 563
mehdi Avatar asked Dec 13 '22 12:12

mehdi


1 Answers

You can't modify a String directly, but you can either use a StringBuilder:

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

.. or convert it to a char[] and back

str = "hi john";
char[] chars = str.toCharArray();
chars[3] = 'g';
str = new String(chars);
like image 56
Landei Avatar answered Jan 06 '23 06:01

Landei