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.");

}

}

}

相关推荐
UFIT几秒前
NoSQL之redis哨兵
java·前端·算法
喜欢吃燃面1 分钟前
C++刷题:日期模拟(1)
c++·学习·算法
刘 大 望4 分钟前
数据库-联合查询(内连接外连接),子查询,合并查询
java·数据库·sql·mysql
ai大师8 分钟前
(附代码及图示)Multi-Query 多查询策略详解
python·langchain·中转api·apikey·中转apikey·免费apikey·claude4
怀旧,10 分钟前
【数据结构】6. 时间与空间复杂度
java·数据结构·算法
小小爬虾29 分钟前
关于datetime获取时间的问题
python
大春儿的试验田1 小时前
Parameter ‘XXX‘ not found. Available parameters are [list, param1]
java
roman_日积跬步-终至千里1 小时前
【Go语言基础【14】】defer与异常处理(panic、recover)
golang
2301_797604241 小时前
学习记录:DAY32
学习
我很好我还能学1 小时前
【面试篇 9】c++生成可执行文件的四个步骤、悬挂指针、define和const区别、c++定义和声明、将引用作为返回值的好处、类的四个缺省函数
开发语言·c++