What is the usage of replaceFirst in Java?

In Java, the replaceFirst method is used to replace the first occurrence of a substring in a string. The syntax is as follows:

public String replaceFirst(String regex, String replacement)

The regex represents the regular expression to match, while the replacement represents the string used to replace the matching substring.

For example, if we have a string “Hello, World, Hello” and we want to replace the first occurrence of “Hello” with “Hi”, we can use the replaceFirst method.

String str = "Hello, World, Hello";
String newStr = str.replaceFirst("Hello", "Hi");
System.out.println(newStr); // 输出:Hi, World, Hello

It should be noted that the replaceFirst method only replaces the first matching substring. If you want to replace all matching substrings, you can use the replaceAll method.

Leave a Reply 0

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