2

I have a string. I want to replace a character in this string, with another string. How do I do that please ?

For example i have aaaaa i want to replace the first 'a' with "bbbb"

for(i=0; i<aString.length()-1; i++){
    if(aString.charAt(i)...some condition)
        charAt(i) replace with some other string
}

Thats what im trying to do

2
  • 2
    Would replaceFirst not do what you want? Commented Jan 13, 2019 at 13:16
  • If you want to replace a char with string, better use concatenation. Commented Jan 13, 2019 at 13:20

1 Answer 1

4

For your specific problem( replacing the first 'a'):

public String replaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular expression with the given replacement.

That is:

String s="aaaaa";
String res=s.replaceFirst("a","bbbb");

For a general solution:

public StringBuilder replace(int start, int end, String str)

Parameters:

start - The beginning index, inclusive.

end - The ending index, exclusive.

str - String that will replace previous contents.

That is:

String s="aaaaa";
StringBuilder sb=new StringBuilder(s);
String res=sb.replace(0,1,"bbbb").toString();   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.