温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java字符串查找如何实现

发布时间:2025-03-01 09:55:44 来源:亿速云 阅读:124 作者:小樊 栏目:编程语言

在Java中,有多种方法可以实现字符串查找。以下是一些常用的方法:

  1. 使用indexOf()方法:
String str = "Hello, World!";
String searchStr = "World";
int index = str.indexOf(searchStr);
if (index != -1) {
    System.out.println("字符串找到,位置为:" + index);
} else {
    System.out.println("字符串未找到");
}
  1. 使用lastIndexOf()方法:
String str = "Hello, World!";
String searchStr = "o";
int index = str.lastIndexOf(searchStr);
if (index != -1) {
    System.out.println("字符串找到,位置为:" + index);
} else {
    System.out.println("字符串未找到");
}
  1. 使用contains()方法:
String str = "Hello, World!";
String searchStr = "World";
boolean contains = str.contains(searchStr);
if (contains) {
    System.out.println("字符串找到");
} else {
    System.out.println("字符串未找到");
}
  1. 使用正则表达式和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("字符串未找到");
        }
    }
}

这些方法都可以实现字符串查找,你可以根据具体需求选择合适的方法。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI