Tuesday, August 10, 2021

Java String Replace Example Tutorial

This String replace example in Java will show you how to replace String in Java both at the character level and by using regular expression. Since String is final in Java every time you replace String you will get a new String object only if your actually replace anything on original String otherwise replace methods of String return same String object. String Class in Java provides 4 methods to replace String in Java. Those methods allow you to replace character from String, replace CharacterSequence from String, replace all occurrence of pattern in String or just first occurrence of any pattern in Java.


We will also see important points on the String replace method and how to make best use of regular expression while replacing string in Java.

This article is on series of my other String article like 2 ways to Split String in Java and how to convert String to Date in Java. String is one of the most important classes in Java and having a good knowledge of String class is mandatory for any Java developer.

Java String Replace Example and Tutorial in Java


Java String replace example tutorial

String Replace Examples in Java

As I said earlier Java provides at-least four methods to replace String in Java according to JDK 1.6 documentation.



1. Replace method to replace single character in String


replace(char oldChar, char newChar)

This replace method in String takes one character and replaces all of its occurrence in provided
String with new character provided to it. Here is an String replace Example of changing character

String replaceSample = "This String replace Example shows how to replace one char from String";
String newString = replaceSample.replace('r', 't');

Output: This Stting teplace Example shows how to teplace one chat ftom Stting


You can see all occurrence of "r" has been replaced by "t".

Important points:
1. This replace method of String will return a new String object if there is a replace.
2. It will return same String objects if there is no matching char and there is no replace.
3. Replacement of String is Case Sensitive, so replacing "c" will only replace small case not Capital Case.

2. Replace method to replace character sequence in String


replace(CharSequence target, CharSequence replacement)

This String replace method replaces one character sequence with other. This method has added from JDK 1.5 onwards. Here is a String replace example of replacing character sequence form String

String replaceSample = "String replace Example of replacing Character Sequence";
String newString = replaceSample.replace("re", "RE");

Output: String REplace Example of REplacing Character Sequence

In this String replace Example, we have replaced "re" with "RE".

Important points:
1) This String replace method will throw NullPointerException if either oldCharSequence or newCharSequence is null.
2) Replacement of String starts from beginning and proceed towards end. So in a String "ccc" replacing "cc" with "d" will result in "dc" rather than "cd".


3. Replace method to replace all matched pattern in String


replaceAll(String regex, String replacement)

Good thing about replace method of String Class in Java is that it supports regular expression. With regex capability you can perform sophisticated Search on String and than replace characters. This String replace method replaces each matched substring with the replacement String provided. Let's see String replace example with regular expression:

String replaceSample = "String replace Example with regular expression";
String newString = replaceSample.replaceAll("^S","R");

Output: Rtring replace Example with regular expression

This String replace replaces any "S" wiht "R" if it comes at beginning of line "^" denotes beginning of line you can also apply pattern matching wildcards and charset while replacing String in Java.


Important points:
1. This String replace method will throw PatternSyntaxException in case regular expression's syntax is not valid.

4. Replace method to replace first matched pattern in String


replaceFirst(String regex, String replacement)

This String replace method is similar to the above method but it only replaces the first occurrence of the matching pattern instead of all occurrences. Very handy sometimes. Here is an example of String replace with replaceFirst() method.

String replaceSample = "String replace Example with replaceFirst";
String newString = replaceSample.replaceFirst("re","RE");

Output: String REplace Example with replaceFirst

You can see only the first occurrence of "re" is replaced with "RE" while the second occurrence remains the same

That’s all on how to replace String in Java, search and replace is one of the most needed things in String and having an idea of the right way of doing it is good. These String replace examples are rather simple but you can make them more sophisticated by using regular expression.


Other Java Tutorials

5 comments :

Anonymous said...

You can also use java.util.regex package to split String using regular expression in Java.

Jimmy said...

Some time regular expression required to be provided in form "\\(.*)" can you explain why does "\\" is needed in string replace method ?

Unknown said...

hi every body. Can you write a program for two strings are equal or not,without using a single API Functions/Methods(Library functions).

Anonymous said...

String a="MXLXYXLXM";
String b=a.replace(3,'X','A');
While compiling it shows me a error that method(into,char,char) not found.could anyone please explain me this.

Anonymous said...

class df
{
static void main(String a,String b)
{
if(a==b)
{System.out.println("the strings are equal");
}
else
{
System.out.println("strings are not equal");
}
}
}

Post a Comment