如:在在ABCDEJXBDHCJSBJXzh中查找JXB在哪个位置
方法一:使用字符串的indexof()方法 。
时间复杂度:O(n * m),其中 n 是文本长度,m 是模式串长度。
空间复杂度:O(1)
public class Main {
public static void main(String[] args) {
String text = "ABCDEJXBDHCJSBJXzh";
String pattern = "JXB";
int index = text.indexOf(pattern);
if (index != -1) {
System.out.println("使用 indexOf() 方法找到匹配的字符串,位置在:" + index);
} else {
System.out.println("未找到匹配的字符串。");
}
}
}
方法二:正则表达式方法。
时间复杂度:通常情况下是 O(n),其中 n 是文本长度。
空间复杂度:O(1)或O(n)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class A0 {
public static void main(String[] args) {
String text = "ABCDEJXBDHCJXBJXzhjxbjxbjxbJXBJXBJXB";
String pattern = "JXB";
Pattern p = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);
if (m.find()) {
System.out.println("使用正则表达式找到匹配的字符串,位置在:" + m.start()+" "+m.end());
String S= m.replaceAll("zzz");
System.out.println(S);
} else {
System.out.println("未找到匹配的字符串。");
}
}
}
当然,还有许多好的方法,有兴趣的可以自己去学习以下。