Java String Translate translate(String sequence, String match, String replacement)

Here you can find the source of translate(String sequence, String match, String replacement)

Description

This method is used to translate characters in the input sequence that match the characters in the match list to the corresponding character in the replacement list.

License

Open Source License

Parameter

Parameter Description
sequence The input sequence to be processed
match The list of matching characters to be searched
replacement The list of replacement characters, positional coincident with the match list. If shorter than the match list, then the position "wraps" around on the replacement list.

Return

The translated string contents.

Declaration

public static Object translate(String sequence, String match, String replacement) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from   www .  j  a  va  2s .c  o m*/
     * This method is used to translate characters in the input sequence that match the characters in the match list to
     * the corresponding character in the replacement list. If the replacement list is shorter than the match list, then
     * the character from the replacement list is taken as the modulo of the match character position and the length of
     * the replacement list.
     * 
     * @param sequence
     *            The input sequence to be processed
     * @param match
     *            The list of matching characters to be searched
     * @param replacement
     *            The list of replacement characters, positional coincident with the match list. If shorter than the
     *            match list, then the position "wraps" around on the replacement list.
     * @return The translated string contents.
     */
    public static Object translate(String sequence, String match, String replacement) {

        if (sequence == null) {
            return sequence;
        }

        StringBuffer buffer = new StringBuffer(sequence);

        for (int index = 0; index < buffer.length(); index++) {
            char ch = buffer.charAt(index);

            int position = match.indexOf(ch);
            if (position == -1) {
                continue;
            }

            if (position >= replacement.length()) {
                position %= replacement.length();
            }
            buffer.setCharAt(index, replacement.charAt(position));
        }

        return buffer.toString();
    }
}

Related

  1. translate(String originalHtml)
  2. translate(String s)
  3. translate(String s)
  4. translate(String s, String identifier, String associator)
  5. translate(String s, String oldChars, String newChars)
  6. translate(String source)
  7. translate(String str, String searchChars, String replaceChars)
  8. translate(String str, String searchChars, String replaceChars)
  9. translate(String str, String searchChars, String[] replaceStrings)