您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,可以使用以下几种方法来高效地查找子字符串:
indexOf()
方法:这是Java中最常用的查找子字符串的方法。它返回子字符串在源字符串中首次出现的位置,如果没有找到子字符串,则返回-1。String source = "Hello, world!";
String substring = "world";
int index = source.indexOf(substring);
if (index != -1) {
System.out.println("Substring found at index: " + index);
} else {
System.out.println("Substring not found");
}
lastIndexOf()
方法:与indexOf()
类似,但lastIndexOf()
从源字符串的末尾开始查找子字符串,并返回子字符串最后一次出现的位置。String source = "Hello, world! Welcome to the world!";
String substring = "world";
int index = source.lastIndexOf(substring);
if (index != -1) {
System.out.println("Substring found at index: " + index);
} else {
System.out.println("Substring not found");
}
contains()
方法:这个方法检查源字符串是否包含子字符串,并返回一个布尔值。String source = "Hello, world!";
String substring = "world";
boolean contains = source.contains(substring);
if (contains) {
System.out.println("Substring found");
} else {
System.out.println("Substring not found");
}
Pattern
和Matcher
类来进行正则表达式匹配。import java.util.regex.Matcher;
import java.util.regex.Pattern;
String source = "Hello, world!";
String regex = "world";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
if (matcher.find()) {
System.out.println("Substring found at index: " + matcher.start());
} else {
System.out.println("Substring not found");
}
请注意,正则表达式匹配通常比简单的子字符串查找要慢,因此在性能敏感的情况下,建议使用indexOf()
、lastIndexOf()
或contains()
方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。