I have a string similar to the one below:
String abc = "122222";
and I want to be able to replace a specified character inside string, so the '1' becomes '2' in the example above.
I have a string similar to the one below:
String abc = "122222";
and I want to be able to replace a specified character inside string, so the '1' becomes '2' in the example above.
You should use replaceFirst
if you want to replace only the first 1
String abc = "122222";
abc = abc.replaceFirst("1","2");
because replace
will replace all occurrences of 1
in abc
.
A quick search for the java string API would have given you what you needed. With examples too.
Here i am replacing "2" with "3" test this.
public class TextDemo {
public static void main(String arg[]) {
String a = "11112bbbb";
int b = a.indexOf("2");
String c = a.substring(0, b);
String d = a.substring(b);
String e = d.substring(1);
String f = "3" + e;
String finalString = c + f;
System.out.println(finalString);
}