This Tutorial will Explain all about Java String Replace() Method along with ReplaceAll() and ReplaceFirst() Methods with the help of Examples:
We will also explore a few scenario-based examples and frequently asked questions that will make the concept clear.
Upon going through this tutorial, you will know about the replace(), replaceFirst() and replaceAll() methods and you will be able to use these two methods in String handling problems.
=> Take A Look At The Java Beginners Guide Here.
Table of Contents:
Java String Replace
Before we proceed, we need to know that Java String replace() method has three different variants as mentioned below:
- Java String replace()
- Java String replaceAll()
- Java String replaceFirst()
All these variants have their own significance and these can be used based on the requirement during any String manipulation. Also, each of these methods has its own variants which are discussed along with their syntax and their implementation details in the latter part of this tutorial.
In short, Java String replace() method is used to replace all the occurrences of any given character with a new character.
Java String replaceAll() method works in accordance with the regular expression and based on the regular expression, we are free to choose what type of operation we are going to have on an input String.
Furthermore, the Java String replaceFirst() method is used to replace the first occurring character with a new character.
String Replace() Method
As the name itself suggests, the replace() method is used to replace all the occurrences of a specific character of a String with a new character.
The Java String Replace has two variants as shown below.
#1) The replace method for the character.
The syntax for character replace:
String replace(char originalChar, char replacingChar)
#2) The replace method for the character sequence.
The syntax for character sequence replace:
String replace(CharSequence original, CharSequence replacing)
Replacing A Character
In the below example, we will be initializing a String variable. Then, we will replace any specific character of the String with a new character.
public class replace { public static void main(String[] args) { // Initialized a String String str = "CAT"; // Replaced the character 'C' with 'R' String replace = str.replace('C', 'R'); // Printed the Original String System.out.println("The Original String was: " + str); // Printed the Final String after replace() operation System.out.println("The Final String is: " + replace); } }
Output:
Replacing Character Sequence
In this example, we will discuss about the other form of Java String replace() method.
Syntax:
String replace(CharSequence original, CharSequence replacing)
This form of Java String replace() method replaces one character sequence with the other. In the below example, we will initialize a String variable, and then replace the char sequence with the other.
Let’s see the below example.
public class replace { public static void main(String[] args) { // Initialized a String String str = "Shooting"; // Replaced the character sequence 'oot' with 'out' String replace = str.replace("oot", "out"); // Printed the Original String System.out.println("The Original String was: " +str); // Printed the Final String after replace() char sequence operation System.out.println("The Final String is: " +replace); } }
Output:
String ReplaceAll() Method
This method returns a new String as the output and this new String is based on the outcome of the regular expressions that we provide in the regex.
The syntax for ReplaceAll:
String replaceAll(String regex, String output)
Replacing All Characters
In this example, we will see how the replaceAll() works with regular expressions. In this program, we will replace all the whitespace between characters with a symbol ‘%’ using the replaceAll() method with regular expression.
public class replaceAll { public static void main(String[] args) { // Initialized a String String str = "This is a Testing Website"; /* * Replacing all the whitespaces between * characters with the '%' */ String replaceAll = str.replaceAll("\\s+", "%"); // Printed the Original String System.out.println("Before ReplaceAll() " + str); // Printed the Final String after replaceAll() operation System.out.println("After ReplaceAll(): " + replaceAll); } }
Output:
String ReplaceFirst() Method
Apart from the replace() and replaceAll(), we have another method called replaceFirst() method that is used to replace the first occurring character of any String.
This method returns a new String in which the first character is replaced with a new character. Let’s look into the syntax for more details.
The syntax for ReplaceFirst:
String replaceFirst(char oldFirstChar, char newFirstChar)
Replacing The First Character
In this program, we have taken an input String and tried replacing the first occurring character with a new character using the replaceFirst() method.
Inside the replaceFirst() method, we have passed the old first character and the new first character. The returned String will replace the old first character with the new first character.
public class ReplaceFirst { public static void main(String[] args) { String str = "PPPPP"; System.out.println(str); // Replaced the first occurrence of 'P' with 'Q' String replaceFirst = str.replaceFirst("P", "Q"); System.out.println(replaceFirst); } }
Output:
Scenarios
Scenario 1: Replacing a substring using the Java replaceAll() method.
Explanation: In this scenario, we are going to replace a substring from the main String with a new substring.
In this program, we have made use of the wildcard character ‘*’ that is followed by the String “Fred”. Each occurrence of Fred will be replaced by the new String “Ted”. As we know, a wildcard character is a special character that we can use to represent any other character.
Here, we have used “Fred*” i.e. for every occurrence of “Fred”, “Fredd”, “Fredx”, “Fredy” and so on, it will replace each of them with the new String “Ted.” Also, it will replace the “Freddy” (substring in the input String of the below program) with “Tedy”.
public class replaceAll { public static void main(String[] args) { // Initialized a String String str = "Fred Freddy Franklin Michael Trevor Fredy"; // Replacing the names that start with Fred with the Ted String replaceAll = str.replaceAll("Fred*", "Ted"); // Printed the Original String System.out.println("Before ReplaceAll() " + str); // Printed the Final String after replaceAll() operation System.out.println("After ReplaceAll(): " + replaceAll); } }
Output:
Scenario 2: Replacing a String that starts with a character sequence with a new String.
Explanation: Here, we are going to replace a String that starts with a certain character sequence with a new String. We have used the same input String (as an above scenario), then we have carried out the regex operation using replaceAll.
public class replaceAll { public static void main(String[] args) { // Initialized a String String str = "Fred Freddy Franklin Michael Trevor Fredy"; // Replacing the entire String that starts with Fred with the Ted String replaceAll = str.replaceAll("Fred.*", "Ted"); // Printed the Original String System.out.println("Before ReplaceAll() " + str); // Printed the Final String after replaceAll() operation System.out.println("After ReplaceAll(): " + replaceAll); } }
Output:
Frequently Asked Questions
Q #1) How to change a character using replace() and replaceAll()?
Answer: Changing a character works well with both replace() and replaceAll() methods. Let’s look into the following program for more info.
public class replaceAndReplaceAll { public static void main(String[] args) { // Initialized a String variable String str = "CUT"; // Replaced 'C' with 'P' using replace() method String replace = str.replace('C', 'P'); // Replaced 'C' with 'P' using replaceAll() method String replaceAll = str.replaceAll("C", "P"); // Printed Original String System.out.println("Original String: " +str); // Printed the output of replace() method System.out.println("Replace String: " +replace); // Printed the output of replaceAll() method System.out.println("ReplaceAll String: " +replaceAll); } }
Output:
Q #2) How to replace a character in a String in Java without using the replace() method?
Answer: In the below program we have not used the replace() method to replace the character occurring at index = 2.
public class withoutReplace { public static void main(String[] args) { String str = "This"; // Printed Original String System.out.println(str); // Replacing character at position 2 which is 'i' String replaced = str.substring(0, 2) + 'u' + str.substring(2 + 1); // Printed Replaced String System.out.println(replaced); } }
Output:
Q #3) How to replace the last occurrence of a String in Java?
Answer: In this program, we have used the regular expression with the replaceAll() method to replace the last occurrence of a String.
public class replaceAll { public static void main(String[] args) { // Initialized a String variable String str = "Tony Stark John Jon StarkTony"; /* * '$' means the last element of the matching pattern. * So we have replaced the last occurrence of "Tony" with * "Trevor" using regex = "Tony$" */ String replaceAll = str.replaceAll("Tony$", "Trevor"); // Printed the original element System.out.println(str); // Printed the replaced element System.out.println(replaceAll); } }
Output:
Q #4) How to change String value in Java?
Answer: There are a lot of Java String methods that can change the value of a String.
Let’s look at the replace() method.
public class replace { public static void main(String[] args) { String str = "1000"; System.out.println(str); // Changing the value of the Original String String changed = str.replace("000", "111"); System.out.println(changed); } }
Output:
Q #5) What is a Wildcard Character? Explain.
Answer: A wildcard character is a special character that is used to represent any other character. Any character can be used in the index where we have defined the wildcard character. Some of the common wildcard characters are ‘*’, ‘?’ etc.
Let’s take an example of a String “eat*”. Here, the wildcard character ‘*’ occurs at the last index. This means that the String will always start with “eat” but it is free to choose the ending characters.
So, when you try to search with the input String as “eat*” then the search result can be “eat”, “eaten”, “eatable”, “eating” and so on.
Conclusion
In this tutorial, we have explored the Java String replace() and replaceAll() methods in detail. Apart from these two methods, we also learned about the replaceFirst() method.
Suggested reading =>> MySQL REPLACE Function
Sufficient programming examples have been included in this tutorial, to give you more details into each of these three methods. Regular expression examples were also provided as part of the replaceAll() method.
We hope the scenario-based and Frequently asked questions included in this tutorial would have given you a great insight on Java String Replace.
=> Visit Here To Learn Java From Scratch.