您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,实现字符串搜索有多种方法。以下是一些常用的方法:
indexOf()
方法:String str = "Hello, World!";
String searchTerm = "World";
int index = str.indexOf(searchTerm);
if (index != -1) {
System.out.println("找到搜索词: " + searchTerm + " 在字符串中的位置: " + index);
} else {
System.out.println("未找到搜索词: " + searchTerm);
}
contains()
方法:String str = "Hello, World!";
String searchTerm = "World";
boolean found = str.contains(searchTerm);
if (found) {
System.out.println("找到搜索词: " + searchTerm);
} else {
System.out.println("未找到搜索词: " + searchTerm);
}
Pattern
类:import java.util.regex.Pattern;
import java.util.regex.Matcher;
String str = "Hello, World!";
String searchTerm = "World";
Pattern pattern = Pattern.compile(searchTerm);
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println("找到搜索词: " + searchTerm + " 在字符串中的位置: " + matcher.start());
} else {
System.out.println("未找到搜索词: " + searchTerm);
}
public class KMPAlgorithm {
public static int kmpSearch(String text, String pattern) {
int[] lps = computeLPSArray(pattern);
int i = 0;
int j = 0;
while (i < text.length()) {
if (pattern.charAt(j) == text.charAt(i)) {
i++;
j++;
}
if (j == pattern.length()) {
return i - j;
} else if (i < text.length() && pattern.charAt(j) != text.charAt(i)) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return -1;
}
private static int[] computeLPSArray(String pattern) {
int[] lps = new int[pattern.length()];
int len = 0;
int i = 1;
while (i < pattern.length()) {
if (pattern.charAt(i) == pattern.charAt(len)) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
public static void main(String[] args) {
String str = "Hello, World!";
String searchTerm = "World";
int index = kmpSearch(str, searchTerm);
if (index != -1) {
System.out.println("找到搜索词: " + searchTerm + " 在字符串中的位置: " + index);
} else {
System.out.println("未找到搜索词: " + searchTerm);
}
}
}
这些方法中,indexOf()
和contains()
是最常用的,它们分别返回搜索词在字符串中首次出现的位置和布尔值表示是否找到。正则表达式方法适用于更复杂的搜索模式,而KMP算法在处理大量数据时具有较高的性能。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。