String's replace operation
Java's String class provides four replace methods: replace(char, char), replace(CharSequence, CharSequence), replaceAll(regex, replacement), and replaceFirst(regex, replacement). This article explains the difference between literal and regex-based replacement, how to use backreferences in replaceAll(), and why replaceAll() treats its first argument as a regex while replace() does not.
In this article, we are going to look at how to replace a character or a substring within a String
Contents
Replace all occurrences of a specific character from a string Replace all occurrences of a substring from a string Replace matching pattern substrings from a string using regular expression
Replace all occurrences of a specific character from a string
We can use String.replace(char oldChar, char newChar)oldCharnewChar
For example, in the below example, we will replace 'W''w'"Hello World"public class ReplaceString {
public static void main(String[] args) {
String s1 = "Hello World";
String afterReplacingW = s1.replace('W', 'w');
System.out.println("Before replacing W : "+s1);
System.out.println("After replacing W with lowercase w : "+ afterReplacingW);
}
}
When you run the above program, you will get the below output.
Before replacing W : Hello World
After replacing W with lowercase w : Hello world
Note:
Note that, String.replace(char oldChar, char newChar)oldCharnewChar
Replace all occurrences of a substring from a string
We can use String.replace(CharSequence target, CharSequence replacement)targetreplacement
For example, in the below example, we will replace the substring "World""CsCode""Hello World"public class ReplaceString {
public static void main(String[] args) {
String s2 = "Hello World";
String afterReplacingWorld = s2.replace("World", "CsCode");
System.out.println("Before replacing World : "+s2);
System.out.println("After replacing World with CsCode word : "+ afterReplacingWorld);
}
}
When you run the above program, you will get the below output.
Before replacing World : Hello World
After replacing World with CsCode word : Hello CsCode
Note:
Note that, String.replace(CharSequence target, CharSequence replacement)targetreplacement
Replace matching pattern substrings from a string
We can use String.replaceAll(String regex, String replacement)regexreplacement
For example, in the below example, we will replace space characters " ""%20""url with spaces"public class ReplaceString {
public static void main(String[] args) {
String s3 = "url with spaces";
String afterApplyingRegEx = s3.replaceAll(" ", "%20");
System.out.println("Before formatting url : "+s3);
System.out.println("After formatting url : "+ afterApplyingRegEx);
}
}
When you run the above program, you will get the below output.
Before formatting url : url with spaces
After formatting url : url%20with%20spaces
String.replaceAllString.replaceFirst(String regex, String replacement)
Above example complete source code can be found at