Link to home
Start Free TrialLog in
Avatar of mikekwok
mikekwokFlag for Hong Kong

asked on

String.replaceAll function

I know that if Java 1.4.2 I can use String.replaceall to replace all of the character I specified to another specified character .
However, I am using Java 1.3.1 and I can't use string.replaceall function.  would somebody please teach me how to solve the problem ?

I want to have a function that does the same as string.replaceall. Thanks.

Avatar of zzynx
zzynx
Flag of Belgium image

What about
public String replace(char oldChar, char newChar)
?
Write your own using the functions indexOf() and substring()
Avatar of riaancornelius
riaancornelius

just use a recursive function, that keeps replacing the character, until indexOf() returns -1:
something like this:

public String replaceAll(String oldString, String value, String newValue){
  String newString = oldString.replace(oldValue, newValue)
  if( newString.indexOf(value)!=-1 )
    return replaceAll( newString, value, newValue );
  else
    return newString;
}
   
Avatar of mikekwok

ASKER

What I want to do is :

Check for string if it contain ' , if it is true , then replace the single quote to 2 single quote .... ''

would you please help?
       char singleQuote = '\'';
        char doubleQuote = '\"';
        System.out.println("hello ' all !".replace(singleQuote,doubleQuote));
>> single quote to 2 single quote
Sorry. The previous replaced the single quote by a double quote.
>> replace the single quote to 2 single quote

    public static String doubleTheQuotes(String input) {
        StringBuffer buf = new StringBuffer(input.length());
        for (int i=0; i<input.length(); i++) {
            char c = input.charAt(i);
            if (c=='\'')
                buf.append("''");  // That's a double quote, a single quote, a single quote and a double quote ;°)
            else
                buf.append(c);
        }
        return buf.toString();
    }
ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial