Link to home
Start Free TrialLog in
Avatar of omom
omom

asked on

String - replace substring

How can one replace part of a string with another string?

e.g. Given a string "aaaaabbbbbbccccccdddddd", replace the "bbbbb" with "zzzzz" to make the string "aaaaazzzzzcccccddddd"


You can start with:
int i = fooStringl.indexOf ("bbbbb");

but then using replace() to replace one character at a time is inefficient.  

Converting it to StringBuffer doesn't seem to help, either.
There is insert(), but that's not quite it

Avatar of bbangerter
bbangerter

Try:

String fooString = "aaaaabbbbbcccccddddd";
String barString = "bbbbb";
String replaceString = "zzzzz";
int fooLength = fooString.length ();
int barLength = barString.length ();
int index = fooString.indexOf (barString);

if (index != -1)
{
  String newString = fooString.substring (0, index) + replaceString + fooString.substring (index + barLength, fooLength);
}
else
{
  // barString does not exist inside of fooString - so nothing to replace
}

If there may be more than one instance of barString within fooString and you want to replace all instances of barString, then you will need to iterate through this code until index == -1



From bbangerter 's comment. I think that code should be.

if (index != -1) {
  fooString  = fooString.substring (0, index) + replaceString +
      fooString.substring (index +  barLength, fooLength);
}

Avatar of omom

ASKER

Close enough, lock if you want to.
Avatar of omom

ASKER

I think bbangerter should get the points
Avatar of omom

ASKER

I think bbangerter should get the points
ASKER CERTIFIED SOLUTION
Avatar of bbangerter
bbangerter

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial