user1891916
user1891916

Reputation: 1001

achieve replaceAll functionality 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 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

Answers (1)

Makoto
Makoto

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:

  • Create a StringTokenizer instance
  • Consume the string via the tokenizer and place it into the StringBuffer
  • Immediately after the string is consumed, place "%20" after it
  • Do not add the previous string if there are no more tokens to add

As 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

Related Questions