Java String replace

Filed Under: Java

Java String replace methods are used to replace part of the string with some other string. These string replace methods are sometimes very useful; for example replacing all occurrence of “colour” to “color” in a file.

Java String replace

Java String replace
Java String class has four methods to replace a substring. Two of these methods accept regular expressions to match and replace part of the string.

  1. public String replace(CharSequence target, CharSequence replacement): This method replaces each substring of this string with the replacement string and return it. Note that replacement happens from start of the string towards end of the string. This behaviour can be easily confirmed by below code snippet.
    
    String str1 = "aaaaa";
    str1 = str1.replace("aa","x");
    System.out.println(str1); //xxa
    
  2. public String replace(char oldChar, char newChar): This method is used to replace all occurrences of oldChar character to newChar character.
  3. public String replaceAll(String regex, String replacement): This is a very useful method because we can pass regex to match and replace with the replacement string.
  4. public String replaceFirst(String regex, String replacement): This string replacement method is similar to replaceAll except that it replaces only the first occurrence of the matched regex with the replacement string.

Let’s look into java string replace methods with example code.

Java String replace character example

One of the popular use case for character replacement is to change a delimiter in a string. For example, below code snippet shows how to change pipe delimiter to comma in the given string.


package com.journaldev.string;

public class JavaStringReplaceChar {

	public static void main(String[] args) {
		
		String str = "Android|java|python|swift";
		str = str.replace('|', ',');
		System.out.println(str);
	}
}

java string replace char

Java String replace() example

Let’s look at java string replace method example to replace target string with another string. I will take user input from java scanner class for source, target and replacement strings.


package com.journaldev.string;

import java.util.Scanner;

public class JavaStringReplace {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Enter Source Term:");
		String source = sc.nextLine();

		System.out.println("Enter Search Term:");
		String search = sc.nextLine();

		System.out.println("Enter Replace Term:");
		String replace = sc.nextLine();

		String result = source.replace(search, replace);

		System.out.println("Result = " + result);

		sc.close();
	}

}

Below image illustrates the output of one of the execution of above program.

java string replace example

Java String replaceAll example

If you notice above program output, target string should be an exact match for replacement. Sometimes it’s not possible because the input string may be different because of case. In this scenario we can use replaceAll method and pass regular expression for case insensitive replacement. Let’s look at a simple program where we will match and replace string with case insensitivity.


package com.journaldev.string;

import java.util.Scanner;

public class JavaStringReplaceAll {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter Source Term:");
		String source = sc.nextLine();

		System.out.println("Enter Search Term:");
		String search = sc.nextLine();
		search = "(?i)"+search;
		
		System.out.println("Enter Replace Term:");
		String replace = sc.nextLine();
		
		
		String result = source.replaceAll(search, replace);
		
		System.out.println("Result = "+result);
		
		sc.close();
	}

}

Did you notice the prefix (?i) to the search term? This is to pass regex to match strings with case insensitive way. Below image shows the output where both “Android” and “android” terms are getting replaced with “Java” because we used replaceAll method.
java string replaceAll example

Java String replaceFirst example

Java String replaceFirst is used to replace only the first matched regex string with the replacement string. Let’s look at a simple example of String replaceFirst method.


package com.journaldev.string;

public class JavaStringReplaceFirst {

	public static void main(String[] args) {
		String str = "Hello JournalDev Users";
		
		str = str.replaceFirst("Hello", "Welcome");
		System.out.println(str);
		
		String str1 = "HELLO Java String Tutorial";
		str1 = str1.replaceFirst("(?i)"+"hello", "Welcome to");
		System.out.println(str1);
	}

}

java string replaceFirst example

That’s all for java String replace methods with example code.

Reference: String API Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages