qazmlp said:
I have a string like this: "one\\two\\three\\"
I want to replace 2 continuous slashes that figure in the string with
4 continuous slashes.
After replacement, the string will look like
this:"one\\\\two\\\\three\\\\"
Can this be done with the String functions available in Java-1.2?
If yes, kindly help me how to do it.
Thanks!
Something like this?
import java.util.StringTokenizer;
public class StringReplacer {
private static String sDelim = ":";
private String fReplacement;
public StringReplacer(String replacement){
if (replacement == null){
throw new NullPointerException("replacement cannot be null");
}
fReplacement = replacement;
}
public String replace(String orig, String remove){
String result = null;
String delimited;
StringBuffer buff = new StringBuffer();
int index = orig.indexOf(remove);
if (index > -1){
buff.append(orig.substring(0,index));
int begin = index + remove.length();
index = orig.indexOf(remove, begin);
while (index > 0){
buff.append(sDelim).append(orig.substring(begin, index));
begin = index + remove.length();
index = orig.indexOf(remove, begin);
}
buff.append(sDelim).append(orig.substring(begin,
orig.length()));
delimited = buff.toString();
} else {
delimited = orig;
}
buff.delete(0, buff.length());
StringTokenizer tokenizer = new StringTokenizer(delimited, sDelim,
true);
while (tokenizer.hasMoreTokens()){
String token = tokenizer.nextToken();
if (token.equals(sDelim)){
token = fReplacement;
}
buff.append(token);
}
result = buff.toString();
return result;
}
public static void main(String[] args) {
String original = (args.length > 0) ? args[0] :
"one\\two\\three\\\\";
StringReplacer replacer = new StringReplacer("\\\\\\\\");
String remove = "\\\\";
String result = replacer.replace(original, remove);
System.out.println("Result: " + result);
}
}