如何在 Java 中计算字符串的第一次出现次数
问题描述
如何计算字符串的第一次出现次数?
解决方案
以下示例演示如何使用 Matcher 类的 replaceFirst() 方法替换字符串中第一次出现的字符串。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
Pattern p = Pattern.compile("hello");
String instring = "hello hello hello.";
System.out.println("initial String: "+ instring);
Matcher m = p.matcher(instring);
String tmp = m.replaceFirst("Java");
System.out.println("String after replacing 1st Match: " +tmp);
}
}
结果
上述代码示例将产生以下结果。
initial String: hello hello hello. String after replacing 1st Match: Java hello hello.
java_regular_exp.html

