In this Java tutorial, you will learn how to replace the first occurrence of a string with a replacement string using String.replaceFirst() method, with examples.

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) method.

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() method 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 requirement.

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

Examples

ADVERTISEMENT

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

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.

2. Replace substring in string, but the search string is not present

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

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.