Java学习,字符串搜索

Java 中字符串搜索是一个非常常见的操作,可以使用多种方法来实现字符串搜索,包括使用内置的字符串方法、正则表达式以及第三方库。

indexOf 方法:

indexOf 方法,可以用来查找子字符串,在字符串中第一次出现的位置。如果未找到子字符串,则返回 -1。

示例:

public class StringSearchExample {

public static void main (String[] args) {

String text = "Hello, welcome to the world of Java!";

String searchString = "world";

int index = text.indexOf(searchString);

if (index != -1) {

System.out.println("Found \"" + searchString + "\" at index " + index);

} else {

System.out.println("\"" + searchString + "\" not found.");

}

}

}

contains 方法:

contains 方法,可以用来检查一个字符串是否包含另一个字符串,返回布尔值。

示例:

public class StringContainsExample {

public static void main(String[] args) {

String text = "Hello, welcome to the world of Java programming!";

String searchString = "Java";

if (text.contains(searchString)) {

System.out.println("\"" + searchString + "\" is found in the text.");

} else {

System.out.println("\"" + searchString + "\" is not found in the text.");

}

}

}

相关推荐
超级无敌葛大侠5 分钟前
Redis主从复制
java·redis
研究点啥好呢21 分钟前
字节跳动Go后端开发工程师面试题精选:10道高频考题+答案解析
面试·golang·php·求职招聘
Victory_202521 分钟前
c#定时器顺序控制写法
开发语言·c#·c#顺序控制+定时器
ErizJ24 分钟前
Redis|学习笔记
redis·笔记·学习
Cyber4K38 分钟前
【Python专项】Nginx访问日志分析时间范围处理示例
开发语言·python·nginx
加油20191 小时前
方法论:如何系统性的学习?
学习·学习方法·方法论
中犇科技1 小时前
郑州无代码APP开发公司哪家好呢?推荐
开发语言
周末也要写八哥1 小时前
代码中的注释的重要性(二)
开发语言·python
殷紫川1 小时前
90% Java 开发都踩过坑的 @Resource 与 @Autowired
java
笨笨饿1 小时前
#79_NOP()嵌入式C语言中内联汇编宏的抽象封装模式研究
linux·c语言·网络·驱动开发·算法·硬件工程·个人开发