Reputation: 1001
I have below code
import java.io.*;
public class Test{
public static void main(String args[]){
String Str = new String("Welcome to java world !");
System.out.print("Return Value :" );
System.out.println(Str.replaceAll(" ",
"%20" ));
}
}
This produces the following result:
Return Value :Welcome%20to%20java%20world%20!
But the issue is that i am using legacy java 1.2 in our project there is no support for replaceAll in String class or replace in StringBuffer class. How to achieve replaceAll logic in java 1.2 to replace all space with %20
Upvotes: 3
Views: 286
Reputation: 106430
I'm very serious when I say you should migrate away from 1.2, but even though you're messing with an archaic version, it isn't like you don't have some primitive tools.
StringTokenizer
is available to use, and considering that it can tokenize strings with spaces in it by default, this should give you a leg up on how to solve this problem.
The steps are simple:
StringTokenizer
instanceStringBuffer
"%20"
after itAs a rough, untested* approach, this is something I'd go for:
public String replace(String phrase, String token, String replacement) {
StringTokenizer st = new StringTokenizer(phrase, token);
StringBuffer stringBuffer = new StringBuffer();
while(st.hasMoreTokens()) {
stringBuffer.append(st.nextToken());
stringBuffer.append(replacement);
}
return stringBuffer.toString();
}
*: untestable; I can't won't download a copy of Java 1.2.
Upvotes: 5