JavaDevNotes.com

Java String Replace Tutorial And Examples

The Java String replace method can be used to replace a character or a string sequence from an instance of a String, with a new value of character or a String sequence. This is very useful in problems that needs String manipulations.

Java String replace Character

The String replace method has several variants. The first one is the simplest because it just replace a character from a String, with a new value of the character. Here is the syntax:
public String replace(char oldChar, char newChar)
What this method do is scan the String from left to right, and when it finds an occurrence of oldChar, it is replaced with the value of newChar. The newly formed String is returned to the caller. Here is a simple example:
public class Test {
   public static void main(String[] args) {
      String originalString = "boby";
      String newString = originalString.replace('o', 'a');
      System.out.println( newString );
   }
}
This code will produce the output
baby

Note that the letter o was replaced with letter a.

Here is another example:

public class Test {
   public static void main(String[] args) {
      String originalString = "nabady";
      String newString = originalString.replace('a', 'o');
      System.out.println( newString );
   }
}

The output of this is:

nobody

Note that the letter a was replaced with letter o. Also note that there are two a's in the String and both were replaced. This means that the replace method will replace all occurrences of the given character with the new character value.

Again, consider this example:

public class Test {
   public static void main(String[] args) {
      String originalString = "hello";
      String newString = originalString.replace('E', 'x');
      System.out.println( newString );
   }
}

The output of this is

hello

Notice that the letter e was NOT replaced with x. This is because the parameter supplied is E and not e. It means that the replace method is CASE-SENSITIVE! In simple terms, case sensitive means that the capital letter version of a character is different from the it's lowercase.

Here is another example to illustrate case-sensitive nature of Java String replace method:
public class Test {
   public static void main(String[] args) {
      String originalString = "Excited Eel";
      String newString = originalString.replace('e', 'o');
      System.out.println( newString );
   }
}

Here is the output of the program:

Excitod Eol

Note that only the small case e was replaced and the capital E was left alone.

Java String replace Character Sequence

If what you need to search for and replace is more than one character, there is another variant of the Java String replace method that accepts character sequence as parameters. Here is the syntax:
public String replace(CharSequence target, CharSequence replacement)

Here is a simple example of how to use this method:

public class Test {
   public static void main(String[] args) {
      String originalString = "Give me the toy. I want to play with the toy.";
      String newString = originalString.replace("toy", "ball");
      System.out.println( newString );
   }
}

And here is the output of the program:

Give me the ball. I want to play with the ball.

Note that we passed the Strings toy and ball, both are more than a character long. All the occurrences of toy was replaced with the String ball.

This is very useful for problems where you have place-holder or template, and you just wish to populate with real values later. Here is a sample program that shows a simple letter template:

public class Test {
   public static void main(String[] args) {
      String templateString = "Dear LAST_NAME, FIRST_NAME.  I hope you are doing well Mr. LAST_NAME.";
      String greetings1 = templateString.replace("LAST_NAME", "Doe").replace("FIRST_NAME", "John");
      String greetings2 = templateString.replace("LAST_NAME", "Smith").replace("FIRST_NAME", "George");
      String greetings3 = templateString.replace("LAST_NAME", "Davis").replace("FIRST_NAME", "Anthony");
      System.out.println( greetings1 );
      System.out.println( greetings2 );
      System.out.println( greetings3 );
   }
}

As you could see, the template was used multiple times to produce this output:

Dear Doe, John.  I hope you are doing well Mr. Doe.
Dear Smith, George.  I hope you are doing well Mr. Smith.
Dear Davis, Anthony.  I hope you are doing well Mr. Davis.

Similar to replacing single Character, this variant is also case-sensitive. For example:

public class Test {
   public static void main(String[] args) {
      String originalString = "This Toy is mine.  The toy is not yours.";
      String newString = originalString.replace("toy", "ball");
      System.out.println( newString );
   }
}

The output is this:

This Toy is mine.  The ball is not yours.

Note that only the second occurrence of toy was replaced. This is because the first occurrence has a different case than the original one. Even when only 1 character in the String did not match, it will be ignored by the replace method. E.g. Toy is not equivalent to toy.

What is CharSequence?

Note that the replace method accepts a CharSequence and not specifically only a String. CharSequence is an interface in the Java language that represents a sequence of char values. By default, the known implementing classes of CharSequence are: CharBuffer, Segment, String, StringBuffer, and StringBuilder.

This means that we are not limited to passing a String instance to the Java String replace method. We can pass any of the 5 implementation of CharSequence. For example, here is a valid Java program that passes a StringBuilder to the Java replace method:

public class Test {
   public static void main(String[] args) {
      StringBuilder sbOld = new StringBuilder();
      sbOld.append("toy");
      StringBuilder sbNew = new StringBuilder();
      sbNew.append("ball");
      String originalString = "This is my toy.  This is not your toy.";
      String newString = originalString.replace(sbOld, sbNew);
      System.out.println( newString );
   }
}

And here is the output of the program:

This is my ball.  This is not your ball.

As you could see, it treated the parameters with the same logic as passing a String instance.