Monday, October 17, 2016

How to replace a substring in Java?

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement). This version of the replace() method replaces each substring of this string (on which you call the replace() method) that matches the literal target sequence with the specified literal replacement sequence. For example, if you call "Effective Java".replace("Effective", "Head First") then it will replace "Effective" with "Head First" in the String "Effective Java". Since String is Immutable in Java, this call will produce a new String "Head First Java".

Another important point to note is that the replacement starts from the beginning of the string and continue to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab" i.e. it's left to right replacement. Let's see some code examples and important points about replacing a substring in Java.

Important points about replace() method

Since replace() is overloaded in java.lang.String class, you need to choose the right one for the job. For example replace(char oldChar, char newChar) is used to replace characters on String. You need to use the replace(CharSequence target, CharSequenece replacement) method to replace the substring in Java. Since String implements the CharSequence interface, you can pass a String to this method. You can also pass StringBuffer and StringBuilder because they also implement the CharSequence interface. Let's see some important things about this replace the function of java.lang.String class.

1) The replace(CharSequene target, CharSequence replacement) method replaces target with replacement in the String object it is called on e.g. "Faster".replace("er", "est") will make "Faster" to "Fastest".

2) Apart from String, you can also pass StringBuffer and StringBuilder to this method because they also implement the CharSequence interface.

3) The replace(CharSequence t, CharSequene r) starts replacing substring from beginning and proceeds towards the end. So if you call "bbb".replace("bb", "c") then output will be "cb" and not "bc" because it will replace first "bb" with "c".

4) This method will throw java.lang.NullPointerException if either target or replacement is null.

5) You can only use this method to replace a substring in java from JDK 5 onwards because it was added first in Java 5 only. It's not available to the earlier version of Java.

6) The replace() method replaces all occurrences of a substring in the String it has been called. For example, if you have a string "22332233" and you want to replace "22" with "44" then replace method will change all occurrence of substring "22" with "44" as shown below:

String number = "22332233";
String replaced = number.replace("22", "44");
System.out.println("orginal string: " + number); // print 22332233
System.out.println("replaced string: " + replaced); // print 44334433

6) Don't forget to store the result into a Separate String object, since String is immutable in Java this method cannot change the original String. For example, can you guess what this program will print:

String book = "Effective Programming";
book.replace("Effective", "Head First");
System.out.println("result: " + book); // "Effective Programming" or "Head First Programming"

To your surprise, this program will print "Effective Programming" even after you have called the replace() method and it succeeded. The reason being String is final in Java, so you cannot change the String object once created. Any change on String will create a new String object. If you look at the signature of String method, it returns a replaced String but if you don't store it in a variable then it will be lost.

This is very common error made by Java programmers and then they complain that replace() method is not working in Java, you might have seen lot of forum post on this topic already.

The right way to use the replace method is following:

String book = "Effective Programming";
String replaced = book.replace("Effective", "Head First");
System.out.println("result: " + replaced); // "Head First Programming"

Please see Java: A Beginner's Guide by Herbert Schildt to learn more about how to do String manipulation in Java.

How to replace a substring in Java?

Java Program to replace substring

Here is our sample Java program which will teach you how to use the replace() method of java.lang.String class to replace a substring in Java. It has three examples, first is normal substring replace, second shows that this method replaces all occurrences of substring and third shows that this method starts replacement from beginning and proceeds towards the end, rather than doing right to left replacement.

public class StringReplaceDemo {

  public static void main(String args[]) {

    // we want to replace "Effective Java" to "Head First Java"
    // which means we need to replace substring "Effective" with "Head First"
    // replace() method can do this for you.

    String book = "Effective Java";
    String newBook = book.replace("Effective", "Head First");

    System.out.println("orginal string: " + book);
    System.out.println("replaced string: " + newBook);

    // replacing substring with multiple occurrences
    // Suppose we have a String "11221122" and

    String number = "11221122";
    String replaced = number.replace("11", "33");
    System.out.println("orginal string: " + number);
    System.out.println("replaced string: " + replaced);

    // The replace() method starts replacement from beginning
    String pattern = "aaaaa";
    String changed = pattern.replace("aaa", "ddd");
    System.out.println("orginal string: " + pattern);
    System.out.println("replaced string: " + changed);



original string: Effective Java
replaced string: Head First Java
original string: 11221122
replaced string: 33223322
original string: aaaaa
replaced string: dddaa

You can see that replacement of substring worked as expected as Effective Java is changed to Head First Java by replacing substring "Effective" with "Head First".  We have also tried both numeric and text substring just to show that it work for both kind of data, anyway, they are actually String.

By the way, there is another way to replace substring or characters in given String, by using StringBuffer or StringBuilder as shown below:

This method doesn't create new String and replace the character into existing String, so if you want to change the same String object, you can use the setCharAt(int index) method to replace characters in String. In order to replace substring just replace more characters.

That's all about how to replace a substring in Java. You need to use the replace(CharSequence target, CharSequence replacement) method. You can pass String, StringBuilder or StringBuffer to this method because they all implement CharSequence interface. Just remember that it start replacement from beginning but replaces all occurrences of a substring.

The only problem with this method is that it's only available from JDK 5 onward. If you are still maintaining JDK 1.4 codebase then you need to write your own method or you need to look at some alternatives at Apache Commons library.  If you are new to Java, I suggest you to also build your fundamentals by reading a good core Java book e.g. Java How to Program by Dietel and Dietel.

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass

Other Java String tutorials for Programmers
  • How to convert String to Date in Java? (tutorial)
  • How to check if given String is Numeric in Java? (solution)
  • How to parse String to float in Java? (tutorial)
  • When should you use the intern() method of String? (article)
  • How to split String by delimiter in Java? (tutorial)
  • How to convert char to String in Java? (tutorial)
  • How to split a String by whitespace or tabs in Java? (tutorial)
  • How to check if one String contains another Substring? (example)
  • How to join String by a delimiter in Java 8? (tutorial)
  • How to add leading zeros to an Integer in Java? (tutorial)
  • How to compare two String in Java? (tutorial)
  • How to replace String in Java? (example)
  • How to concatenate String in Java? (example)
  • Top 10 Java String Interview Questions with answers (list)
  • The right way to check if String is empty in Java? (tutorial)
  • How to format a String in Java? (tutorial)

No comments :

Post a Comment