Replace a char in a string with another string?

Viewed 132

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

1 Answers

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