Replace the first occurrence of a substring

To replace the first occurrence of a string old_string in str1 with new_string, you can use str1.replaceFirst(old_string, new_string) function.

In your application, when working on string processing or some cleaning, you may need to replace some occurrences of words with others. For instance, you may need to replace the first occurrence of some word in all the lines of your text file.

In this tutorial, we will learn the syntax of String.replaceFirst() function and how to use it to replace the first occurrence of a string in another string.

The syntax of String.repalceFirst() is given below.

public String replaceFirst(String regex, String replacement)

For regex, you can provide the old string you would like to replace. You may provide a string constant or some regex, based on your Java application’s requirement.

For replacement, provide the new string you would like to replace with.

Example 1 – Replace First Occurrence with New Substring

In this example, we shall take three strings: str1, old_string and new_string. We shall replace the first occurrence of the string old_string with new_string in str1.

Example.java

/**
 * Java Example Program, to replace first occurrence of a sub-string with another in a string using Java
 */

public class Example {

	public static void main(String[] args) {
		String str1 = "Hi! Good morning. Have a Good day.";
		String old_string = "Good";
		String new_string = "Very-Good";
		
		//replace first occurrence
		String resultStr = str1.replaceFirst(old_string, new_string);
		
		System.out.println(resultStr);
	}
}

Run the above Java program in console or your favorite IDE, and you shall see an output similar to the following.

Output

Hi! Very-Good morning. Have a Good day.

Only the first occurrence is replaced. Other occurrences are unaffected.

Example 2 – Replace First Occurrence with New Substring – Negative Scenario

In this example, we shall take three strings: str1, old_string and new_string. We shall try to replace the first occurrence of the string old_string with new_string in str1. But old_string is not present in str1.

Example.java

/**
 * Java Example Program, to replace first occurrence of a sub-string with another in a string using Java
 */

public class Example {

	public static void main(String[] args) {
		String str1 = "Hi! Good morning. Have a Good day.";
		String old_string = "Bad";
		String new_string = "Very-Good";
		
		//replace first occurrence
		String resultStr = str1.replaceFirst(old_string, new_string);
		
		System.out.println(resultStr);
	}
}

Run the above program.

Output

Hi! Very-Good morning. Have a Good day.

The the old_string is not present in str1, as a result, replaceFirst() returns str1 unchanged.

Conclusion

In this Java Tutorial, we have learned how to replace the first occurrence of a sub-string with another in a string.