java字符串查找的形式有哪些

48次阅读
没有评论

共计 891 个字符,预计需要花费 3 分钟才能阅读完成。

在 Java 中字符串查找的形式有以下几种:

  1. 使用 indexOf() 方法:该方法返回指定子字符串第一次出现的索引,如果未找到则返回 -1。

例如:

String str = "Hello, world!";
int index = str.indexOf("world");
System.out.println(index); // 输出 6
  1. 使用 lastIndexOf() 方法:该方法返回指定子字符串最后一次出现的索引,如果未找到则返回 -1。

例如:

String str = "Hello, world!";
int index = str.lastIndexOf("o");
System.out.println(index); // 输出 8
  1. 使用 contains() 方法:该方法用于判断字符串中是否包含指定的子字符串,返回 true 或 false。

例如:

String str = "Hello, world!";
boolean contains = str.contains("world");
System.out.println(contains); // 输出 true
  1. 使用 matches() 方法:该方法用于判断字符串是否匹配指定的正则表达式。

例如:

String str = "Hello, world!";
boolean isMatch = str.matches("Hello.*");
System.out.println(isMatch); // 输出 true
  1. 使用 startsWith() 和 endsWith() 方法:这两个方法分别用于判断字符串是否以指定的前缀开始或以指定的后缀结束,返回 true 或 false。

例如:

String str = "Hello, world!";
boolean startsWith = str.startsWith("Hello");
boolean endsWith = str.endsWith("world!");
System.out.println(startsWith); // 输出 true
System.out.println(endsWith); // 输出 true

这些方法可以根据具体的需求选择合适的方式进行字符串查找。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-04-07发表,共计891字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)