-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.

1
  • "122222".replace("1","2"); Commented May 15, 2013 at 7:51

6 Answers 6

4
String abc = "122222";
abc = abc.replace('1','2');
Sign up to request clarification or add additional context in comments.

4 Comments

It's Java, so you need to use double quotes.
@enrmarc no. there are two replace methods.
even single quote is fine
@MarcoForberg you are right. I learned something new today.
4

Simply do:

abc = abc.replace('1', '2');

Comments

3

Use the replace() method of String

String abc = "122222";
abc = abc.replace("1", "2");

Comments

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.

Comments

1

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

2 Comments

This should rather be a comment than an answer
Teaching the man to fish
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);

}

2 Comments

a bit complicated and you forgot to check whether indexOf() returned -1
@Macro Forberg I have given basic idea , need some validation check..:)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.