javawaveblogs-20

Tuesday, March 3, 2009

Java method to replace every occurences of a string within another string


/**
* This method will replace every occurences of a string within another
* string.
*
* @param target
* is the original string
* @param from
* is the string to be replaced
* @param to
* is the string which will used to replace
* @return
* changed new string
*/
public static String replace(String target, String from, String to)
{
int start = target.indexOf(from);
if (start == -1)
{
return target;
}
int fromLength = from.length();
char[] targetChars = target.toCharArray();
StringBuffer buffer = new StringBuffer();
int copyFrom = 0;
while (start != -1)
{
buffer.append(targetChars,
copyFrom,
start - copyFrom);
buffer.append(to);
copyFrom = start + fromLength;
start = target.indexOf(from,
copyFrom);
}
buffer.append(targetChars,
copyFrom,
targetChars.length - copyFrom);
return buffer.toString();
}

No comments:

diggthis