Grails Cookbook - A collection of tutorials and examples

String Replace In Java

The Java String Replace is a method which can be applied if there's a new value of character or a String sequence that needs replacement. This method is valuable when you decide changes in Java String, and this post will introduce how to operate such method. By the end of this, we shall be able to use it.

Replace Character in a String

Our topic has numerous alternatives and let's discuss the simple variant. As mentioned a while ago, java string replace method is uncomplicated because
it just substitute a new value of a character from a string.

Check out the syntax below:

public String replace(char oldChar, char newChar)
The purpose of this syntax is that it reads the String from left to right. The value of oldChar will then be replaced with the newly inputted value of newChar. This of it this way, there are only 5 active basketball players playing inside the basketball court and the coach wishes to substitute the point guard. He will then call for a substitute so that the newly chosen point guard can play, the previous active player shall now sit on the team's bench. Back to the String Replace, the newly formed String value will go back to the caller, just like the previous point guard who returned to the coach.

Check out simple written program for a better understanding:

public class Test {
   public static void main(String[] args) {
      String originalString = "bin";
      String newString = originalString.replace('i', 'e');
      System.out.println( newString );
   }
}
ben
Notice the swapping of the letters i and e? This is Java String Replace.

This is another example, check this out:

public class Test {
   public static void main(String[] args) {
      String originalString = "feet";
      String newString = originalString.replace('e', 'o');
      System.out.println( newString );
   }
}
Now look at the expected result:
foot
Notice that both two letters were replaced in the String, implying that when doing this type of method, all occurences of the given character shall be replaced with the new value.

Let us now try with a different approach:

public class Test {
   public static void main(String[] args) {
      String originalString = "hey";
      String newString = originalString.replace('E', 'o');
      System.out.println( newString );
   }
}
Check out the result below:
hello
While we attempt to replace e with o, the output shown was unsuccessful. The reason behind this is that the parameter indicated was E rather than e. In java programming, let us not forget about CASE-SENSITIVE. The uppercase version is not the lowercase version, that's why it is different and will not clearly be replaced.

This is another example that will demonstrate the case-sensitive nature of our topic:

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

Replace Character Sequence In String

There is another preference that takes character sequence as parameters when you want to substitute a character that's greater than one. Observe the written syntax below:
public String replace(CharSequence target, CharSequence replacement)
This simple program will let you understand the method:
public class Test {
   public static void main(String[] args) {
      String originalString = "Can I have one ketchup sauce please, one will do.";
      String newString = originalString.replace("one", "two");
      System.out.println( newString );
   }
}
Observe the output shown below:
Can I have two ketchup sauce please, two will do.
We replaced one with two, and if you noticed there are two one's we've changed. This is because all the occurences of ones has been applied when we switched the Strings.

Consider this method a great convenience when you encounter creating templates or place-holder. Check out the sample program that demonstrates a letter template that's applied with Java String Replace:

public class Test {
   public static void main(String[] args) {
      String templateString = "Dear LAST_NAME, FIRST_NAME.  Upon reading the message you've send, I agree to the terms of your deal. Thank you, Mr. LAST_NAME.";
      String greetings1 = templateString.replace("LAST_NAME", "Smith").replace("FIRST_NAME", "John");
      String greetings2 = templateString.replace("LAST_NAME", "Crow").replace("FIRST_NAME", "David");
      String greetings3 = templateString.replace("LAST_NAME", "Rodriguez").replace("FIRST_NAME", "Edward");
      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 John, Smith.  Upon reading the message you've send, I agree to the terms of your deal. Thank you, Mr. Smith. 
Dear David, Crow.  Upon reading the message you've send, I agree to the terms of your deal. Thank you, Mr. Crow.
Dear Rodriguez, Edward.  Upon reading the message you've send, I agree to the terms of your deal. Thank you, Mr. Rodriguez. 

Remember when we considered case-sensitive in replacing single character? Let's try it in this simple program:
public class Test {
   public static void main(String[] args) {
      String originalString = "Can I have one ketchup sauce please, One will do.";
      String newString = originalString.replace("one", "two");
      System.out.println( newString );
   }
}
Observe what happen below:
Can I have two ketchup sauce please, One will do.
Notice that not all the occurences were changed, the first one string was replaced but the second was unsuccesful. The reason behind this is the case-sensitive, the second string that we're attempting to manipulate did not match with the string we've passed, seeing that, the Java String Replace method was unable to read and execute what the argument commands. Understand that One is not the same with one.

What is CharSequence?

CharBuffer, Segment, String, StringBuffer, and StringBuilder are the known application classes of CharSequence. Now let's define first what is CharSequence, it is an interface in Java language that reads a sequence of character values. In relation with java string replace, Charsequence is also accepted by this method.

We should be aware that when it comes to passing a String instance to the replace method, consider ourselves limitless. You can choose any of the given implementations of CharSequence for your benefit.

Check out the written program that demonstrates the process of CharSequence StringBuilder in relation to java replace method:

public class Test {
   public static void main(String[] args) {
      StringBuilder sbOld = new StringBuilder();
      sbOld.append("ball");
      StringBuilder sbNew = new StringBuilder();
      sbNew.append("ring");
      String originalString = "That is my ball. That is not your ball."; 
      String newString = originalString.replace(sbOld, sbNew);
      System.out.println( newString );
   }
}
Now check out the result below:
That is my ring. That is not your ring.
As you recognized, the parameters used behaved with the same process as passing a String instance.