Java String Translate translate(String s, String oldChars, String newChars)

Here you can find the source of translate(String s, String oldChars, String newChars)

Description

Translate characters from the String inStr found in the String oldChars to the corresponding character found in newChars.

License

Open Source License

Declaration

public static final String translate(String s, String oldChars, String newChars) 

Method Source Code

//package com.java2s;

public class Main {
    /** Translate characters from the String inStr found in the String oldChars to the corresponding
     *  character found in newChars.  If a character occurs in oldChars at a position beyond the
     *  end of newChars, the character is removed.  This function is an analog of the SQL function
     *  TRANSLATE().  By setting newChars to empty String (""), it functions as a
     *  strip-oldChars-from-inStr function.
     *///from  ww w  .j  av  a  2 s.  co  m
    public static final String translate(String s, String oldChars, String newChars) {
        if (s == null || s.length() == 0)
            return s; // nothing to do
        StringBuffer outBuf = new StringBuffer(s.length()); //result can't be bigger
        int idx = -1;
        int limit = s.length();
        for (int i = 0; i < limit; ++i) {
            char c = s.charAt(i);
            if ((idx = oldChars.indexOf(c)) != -1) { // found the character in oldChars!
                if (idx < newChars.length()) { // it has a mapping in the newChars set
                    outBuf.append(newChars.charAt(idx));
                }
            } else {
                outBuf.append(c); // character wasn't in oldChars
            }
        }
        return outBuf.toString();
    }
}

Related

  1. translate(String name, int type)
  2. translate(String originalHtml)
  3. translate(String s)
  4. translate(String s)
  5. translate(String s, String identifier, String associator)
  6. translate(String sequence, String match, String replacement)
  7. translate(String source)
  8. translate(String str, String searchChars, String replaceChars)
  9. translate(String str, String searchChars, String replaceChars)