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
e.g. Given a string "aaaaabbbbbbccccccdddddd",
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
From bbangerter 's comment. I think that code should be.
if (index != -1) {
fooString = fooString.substring (0, index) + replaceString +
fooString.substring (index + barLength, fooLength);
}
if (index != -1) {
fooString = fooString.substring (0, index) + replaceString +
fooString.substring (index + barLength, fooLength);
}
ASKER
Close enough, lock if you want to.
ASKER
I think bbangerter should get the points
ASKER
I think bbangerter should get the points
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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