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

omomAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

bbangerterCommented:
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



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

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

0
omomAuthor Commented:
Close enough, lock if you want to.
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

omomAuthor Commented:
I think bbangerter should get the points
0
omomAuthor Commented:
I think bbangerter should get the points
0
bbangerterCommented:
locked
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.