Java String replace character by character

Introduction

Replaces all occurrences of a character in a String with another.

This is a null-safe version of String#replace(char, char).

A null string input returns *null.

An empty ("") string input returns an empty string.

replaceChars(null, *, *)        = null
replaceChars("", *, *)          = ""
replaceChars("abcba", 'b', 'y') = "aycya"
replaceChars("abcba", 'z', 'y') = "abcba"
public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "test from demo2s.com";
    char searchChar = 't';
    char replaceChar = 'T';
    System.out.println(replaceChars(str, searchChar, replaceChar));
  }/*from  w w  w  . j  a v a2  s .  co m*/
  public static String replaceChars(String str, char searchChar, char replaceChar) {
    if (str == null) {
      return null;
    }
    return str.replace(searchChar, replaceChar);
  }
}



PreviousNext

Related