Java String Translate translate(StringBuffer sb, CharSequence from, CharSequence to)

Here you can find the source of translate(StringBuffer sb, CharSequence from, CharSequence to)

Description

Translate characters.

Each character from[i] in sb is translated to to[i] .

For example translate (sb, "ab", "xy" converts abc to xyc .

License

Open Source License

Declaration

public static final void translate(StringBuffer sb, CharSequence from, CharSequence to) 

Method Source Code

//package com.java2s;
/*/*from w w  w.ja  v a  2 s.  co  m*/
Copyright (?) 2009-2011 Hannu V?is?nen
    
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

public class Main {
    /**
     * Translate characters.<p>
     *
     * Each character {@code from[i]} in {@code sb} is translated to {@code to[i]}.<p>
     *
     * For example {@code translate (sb, "ab", "xy"} converts {@code abc} to {@code xyc}.
     */
    public static final void translate(StringBuffer sb, CharSequence from, CharSequence to) {
        for (int i = 0; i < sb.length(); i++) {
            for (int j = 0; j < from.length() && j < to.length(); j++) {
                if (sb.charAt(i) == from.charAt(j)) {
                    sb.setCharAt(i, to.charAt(j));
                }
            }
        }
    }

    /**
     * Translate characters.<p>
     *
     * Each character {@code from[i]} in {@code s} is translated to {@code to[i]}.<p>
     *
     * For example {@code translate (sb, "ab", "xy"} converts {@code abc} to {@code xyc}.
     */
    public static final String translate(String s, CharSequence from, CharSequence to) {
        StringBuffer sb = new StringBuffer(s);
        translate(sb, from, to);
        return sb.toString();
    }
}

Related

  1. translate(String str, String searchChars, String replaceChars)
  2. translate(String str, String searchChars, String replaceChars)
  3. translate(String str, String searchChars, String[] replaceStrings)
  4. translate(String str, String string_in, String string_out)
  5. translate(String[] ids, String alias)