|
-
Feb 8th, 2002, 01:02 AM
#1
Thread Starter
Randalf the Red
String Replace??
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?
.
-
Feb 8th, 2002, 04:39 AM
#2
Lively Member
Look into method like getString() or StringBuffer() will give u some clue on that...
-
Feb 8th, 2002, 06:28 AM
#3
myString.Replace('a',b');
-
Feb 8th, 2002, 06:55 AM
#4
Thread Starter
Randalf the Red
Well ...
Originally posted by gigsvoo
Look into method like getString() or StringBuffer() will give u some clue on that...
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.
Daok, excuse me, but I have said already that I need a function to replace strings, and not individual characters.
.
Last edited by honeybee; Feb 8th, 2002 at 12:37 PM.
-
Feb 8th, 2002, 08:44 PM
#5
Addicted Member
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;
}
-
Feb 15th, 2002, 05:36 AM
#6
Member
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;
}
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|