Logo Search packages:      
Sourcecode: libcommons-lang-java version File versions  Download package

static String org::apache::commons::lang::StringUtils::replaceChars ( String  str,
String  searchChars,
String  replaceChars 
) [inline, static]

Replaces multiple characters in a String in one go. This method can also be used to delete characters.

For example:
replaceChars("hello", "ho", "jy") = jelly.

A null string input returns null. An empty ("") string input returns an empty string. A null or empty set of search characters returns the input string.

The length of the search characters should normally equal the length of the replace characters. If the search characters is longer, then the extra search characters are deleted. If the search characters is shorter, then the extra replace characters are ignored.

 StringUtils.replaceChars(null, *, *)           = null
 StringUtils.replaceChars("", *, *)             = ""
 StringUtils.replaceChars("abc", null, *)       = "abc"
 StringUtils.replaceChars("abc", "", *)         = "abc"
 StringUtils.replaceChars("abc", "b", null)     = "ac"
 StringUtils.replaceChars("abc", "b", "")       = "ac"
 StringUtils.replaceChars("abcba", "bc", "yz")  = "ayzya"
 StringUtils.replaceChars("abcba", "bc", "y")   = "ayya"
 StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
 

Parameters:
str String to replace characters in, may be null
searchChars a set of characters to search for, may be null
replaceChars a set of characters to replace, may be null
Returns:
modified String, null if null string input
Since:
2.0

Definition at line 2565 of file StringUtils.java.

                                                                                           {
        if (str == null || str.length() == 0 || searchChars == null || searchChars.length()== 0) {
            return str;
        }
        char[] chars = str.toCharArray();
        int len = chars.length;
        boolean modified = false;
        for (int i = 0, isize = searchChars.length(); i < isize; i++) {
            char searchChar = searchChars.charAt(i);
            if (replaceChars == null || i >= replaceChars.length()) {
                // delete
                int pos = 0;
                for (int j = 0; j < len; j++) {
                    if (chars[j] != searchChar) {
                        chars[pos++] = chars[j];
                    } else {
                        modified = true;
                    }
                }
                len = pos;
            } else {
                // replace
                for (int j = 0; j < len; j++) {
                    if (chars[j] == searchChar) {
                        chars[j] = replaceChars.charAt(i);
                        modified = true;
                    }
                }
            }
        }
        if (modified == false) {
            return str;
        }
        return new String(chars, 0, len);
    }


Generated by  Doxygen 1.6.0   Back to index