Is there a function in the Java API to replace strings ? There are methods in the String and StringBuffer objects to replace a single character, but is there any such method for replacing an entire string?
.
Printable View
Is there a function in the Java API to replace strings ? There are methods in the String and StringBuffer objects to replace a single character, but is there any such method for replacing an entire string?
.
Look into method like getString() or StringBuffer() will give u some clue on that...
myString.Replace('a',b');
I searched the Java Language API for JDK 1.2.2 and have found nothing in the String or the StringBuffer class that can give me a clue.Quote:
Originally posted by gigsvoo
Look into method like getString() or StringBuffer() will give u some clue on that...
Daok, excuse me, but I have said already that I need a function to replace strings, and not individual characters.
.
Here y'go honeybee, add this puppy to your class:
Code:/**
* General purpose utility for searching and replacing strings
*/
public String replace(String source, String find, String replace) {
// bail if nothing to look for or replace
String retval = "";
if((find.length() == 0) ||
((replace.length() == 0))) return source;
StringTokenizer st = new StringTokenizer(source, find, true);
try {
while(st.hasMoreTokens()) {
String token = st.nextToken();
retval += token.equals(find) ? replace : token;
}
} catch(Exception e) { // shouldn't happen }
}
return retval;
}
:o sigh.... here is some code that works...
Code:Public class Test {
Public static void main(String[] args) {
System.out.println(Test.replaceStr("ThisABCisABCaABCtest", "ABC", " "));
}
Public static String replaceStr(String replace, String oldStr, String newStr) {
While (replace.indexOf(oldStr) != -1) {
replace = replace.substring(0, replace.indexOf(oldStr)) +
newStr + replace.substring(replace.indexOf(oldStr) + oldStr.length());
}
return replace;
}
}