Achieve function replacement allAll in java 1.2

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 leads to the following result:

Return Value :Welcome%20to%20java%20world%20!

      

But the problem is 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 replace logic replace in java 1.2 to replace all space% 20

+3


source to share


1 answer


I'm serious when I say that you need to upgrade from version 1.2, but even if you've fiddled with the archaic version, it doesn't seem like you don't have primitive tools.

StringTokenizer

can be used, and given that it can block lines with spaces by default, this should give you a leg up on how to fix this issue.

The steps are simple:

  • Create an instance StringTokenizer

  • Use a string with a tokenizer and put it in StringBuffer

  • Immediately after the line is consumed, place "%20"

    after it
  • Don't add the previous line if there are no more tokens to add


As a crude, untested * approach, this is what I would like to do:

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 not download a copy of Java 1.2.

+5


source







All Articles