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

   2024-10-26 7680
核心提示:在Java中字符串查找的形式有以下几种:使用indexOf()方法:该方法返回指定子字符串第一次出现的索引,如果未找到则返回-1。例如

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

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

例如:

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

例如:

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

例如:

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

例如:

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

例如:

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

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

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号