Java String replace multiple characters

Introduction

Replaces multiple characters in a String in one go.

This method can also be used to delete characters.

replaceChars(null, *, *)           = null
replaceChars("", *, *)             = ""
replaceChars("abc", null, *)       = "abc"
replaceChars("abc", "", *)         = "abc"
replaceChars("abc", "b", null)     = "ac"
replaceChars("abc", "b", "")       = "ac"
replaceChars("abcba", "bc", "yz")  = "ayzya"
replaceChars("abcba", "bc", "y")   = "ayya"
replaceChars("abcba", "bc", "yzx") = "ayzya"
public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "test from demo2s.com";
    String searchChar = "te";
    String replaceChar = "ABC";
    System.out.println(replaceChars(str, searchChar, replaceChar));
  }//w w w  .  j  a  v a  2s. c  o m
  public static String replaceChars(String str, String searchChars, String replaceChars) {
    if (isEmpty(str) || isEmpty(searchChars)) {
      return str;
    }
    if (replaceChars == null) {
      replaceChars = EMPTY;
    }
    boolean modified = false;
    int replaceCharsLength = replaceChars.length();
    int strLength = str.length();
    StringBuffer buf = new StringBuffer(strLength);
    for (int i = 0; i < strLength; i++) {
      char ch = str.charAt(i);
      int index = searchChars.indexOf(ch);
      if (index >= 0) {
        modified = true;
        if (index < replaceCharsLength) {
          buf.append(replaceChars.charAt(index));
        }
      } else {
        buf.append(ch);
      }
    }
    if (modified) {
      return buf.toString();
    }
    return str;
  }

  public static boolean isEmpty(String str) {
    return str == null || str.length() == 0;
  }

  public static final String EMPTY = "";
}

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



PreviousNext

Related