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

}

}

}

相关推荐
arvin_xiaoting几秒前
OpenClaw学习总结_I_核心架构_9:Multi-Agent详解
网络·学习·架构·系统架构·ai agent·multi-agent·openclaw
Mike117.5 分钟前
GBase 8a 数据同步实践:从 T+1 同步、实时镜像到一写多读的落地思路
java·服务器·数据库
qq_416018725 分钟前
移动平台C++开发指南
开发语言·c++·算法
站大爷IP6 分钟前
使用 Python 实现 Word 文档文本格式化全解析
python
Nyarlathotep01136 分钟前
LongAdder为什么那么快?
java·后端
自动化智库6 分钟前
西门子S7-1200PLC与V90PN伺服基于FB284模块的定位控制应用
开发语言·科技
3GPP仿真实验室8 分钟前
【MATLAB源码】CSI-RS:信道估计仿真与评估平台
开发语言·matlab
AI-小柒13 分钟前
DataEyes 聚合平台 + Claude Code Max 编程实战
android·开发语言·人工智能·windows·python·macos·adb
王璐WL13 分钟前
【C++】string的经典算法题
开发语言·c++·算法
兑生14 分钟前
【灵神题单·贪心】2279. 装满石头的背包的最大数量 | 排序贪心 | Java
java·开发语言