温馨提示×

温馨提示×

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

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

Java中字符串查找有哪些方法

发布时间:2025-12-14 14:50:58 来源:亿速云 阅读:122 作者:小樊 栏目:编程语言

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

  1. indexOf() 方法 indexOf() 方法用于返回指定子字符串在此字符串中第一次出现处的索引。如果找不到子字符串,则返回 -1。

    String str = "Hello, World!";
    int index = str.indexOf("World"); // 返回 7
    
  2. lastIndexOf() 方法 lastIndexOf() 方法用于返回指定子字符串在此字符串中最后一次出现处的索引。如果找不到子字符串,则返回 -1。

    String str = "Hello, World! World!";
    int index = str.lastIndexOf("World"); // 返回 13
    
  3. contains() 方法 contains() 方法用于判断一个字符串是否包含另一个字符串,如果包含则返回 true,否则返回 false。

    String str = "Hello, World!";
    boolean contains = str.contains("World"); // 返回 true
    
  4. startsWith() 方法 startsWith() 方法用于判断一个字符串是否以指定的前缀开始,如果是则返回 true,否则返回 false。

    String str = "Hello, World!";
    boolean startsWith = str.startsWith("Hello"); // 返回 true
    
  5. endsWith() 方法 endsWith() 方法用于判断一个字符串是否以指定的后缀结束,如果是则返回 true,否则返回 false。

    String str = "Hello, World!";
    boolean endsWith = str.endsWith("World!"); // 返回 true
    
  6. matches() 方法 matches() 方法用于判断一个字符串是否匹配指定的正则表达式。

    String str = "Hello, World!";
    boolean matches = str.matches("Hello, .*!"); // 返回 true
    
  7. split() 方法 split() 方法用于将字符串按照指定的分隔符拆分成字符串数组。

    String str = "apple,banana,cherry";
    String[] fruits = str.split(","); // fruits 数组为 ["apple", "banana", "cherry"]
    

这些方法提供了不同的方式来查找和处理字符串中的子字符串。在实际应用中,可以根据需要选择合适的方法来实现字符串的查找功能。

向AI问一下细节

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

AI
助
手