-1

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.

Robert MacLean
  • 38,975
  • 25
  • 98
  • 152
Vishwanath.M
  • 6,235
  • 11
  • 42
  • 56

6 Answers6

4

Simply do:

abc = abc.replace('1', '2');
Michal Borek
  • 4,584
  • 2
  • 30
  • 40
javic
  • 823
  • 1
  • 6
  • 9
4
String abc = "122222";
abc = abc.replace('1','2');
Marco Forberg
  • 2,634
  • 5
  • 22
  • 33
3

Use the replace() method of String

String abc = "122222";
abc = abc.replace("1", "2");
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
3

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.

Marcos
  • 4,643
  • 7
  • 33
  • 60
1

A quick search for the java string API would have given you what you needed. With examples too.

Dark Star1
  • 6,986
  • 16
  • 73
  • 121
0

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);

}
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52