您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,有多种方法可以实现字符串查找。以下是一些常用的方法:
indexOf()
方法:String str = "Hello, World!";
String searchStr = "World";
int index = str.indexOf(searchStr);
if (index != -1) {
System.out.println("字符串找到,位置为:" + index);
} else {
System.out.println("字符串未找到");
}
lastIndexOf()
方法:String str = "Hello, World!";
String searchStr = "o";
int index = str.lastIndexOf(searchStr);
if (index != -1) {
System.out.println("字符串找到,位置为:" + index);
} else {
System.out.println("字符串未找到");
}
contains()
方法:String str = "Hello, World!";
String searchStr = "World";
boolean contains = str.contains(searchStr);
if (contains) {
System.out.println("字符串找到");
} else {
System.out.println("字符串未找到");
}
Pattern
类:import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
String regex = "World";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println("字符串找到,位置为:" + matcher.start());
} else {
System.out.println("字符串未找到");
}
}
}
这些方法都可以实现字符串查找,你可以根据具体需求选择合适的方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。