温馨提示×

温馨提示×

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

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

Java字符串查找有哪些方法

发布时间:2025-07-23 14:56:05 来源:亿速云 阅读:112 作者:小樊 栏目:编程语言

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

  1. indexOf() 方法

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

    • 返回指定子字符串在此字符串中最后一次出现处的索引。
    • 如果没有找到子字符串,则返回 -1
    String str = "Hello, World! World!";
    int index = str.lastIndexOf("World"); // 返回 13
    
  3. contains() 方法

    • 判断字符串是否包含指定的子字符串。
    • 如果包含,则返回 true;否则返回 false
    String str = "Hello, World!";
    boolean contains = str.contains("World"); // 返回 true
    
  4. startsWith() 方法

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

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

    • 使用正则表达式判断字符串是否匹配指定的模式。
    • 如果匹配,则返回 true;否则返回 false
    String str = "Hello, World!";
    boolean matches = str.matches("Hello, .*!"); // 返回 true
    
  7. replace()replaceAll() 方法

    • replace() 方法用于替换字符串中的所有匹配项。
    • replaceAll() 方法使用正则表达式进行替换。
    String str = "Hello, World!";
    String replacedStr = str.replace("World", "Java"); // 返回 "Hello, Java!"
    
  8. split() 方法

    • 使用指定的分隔符将字符串分割成子字符串数组。
    String str = "apple,orange,banana";
    String[] fruits = str.split(","); // fruits 数组为 ["apple", "orange", "banana"]
    

这些方法提供了不同的方式来查找和处理字符串中的数据。根据具体的需求,可以选择合适的方法来实现字符串的查找和操作。

向AI问一下细节

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

AI