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

}

}

}

相关推荐
奔跑的web.1 天前
TypeScript namespace 详解:语法用法与使用建议
开发语言·前端·javascript·vue.js·typescript
老歌老听老掉牙1 天前
Python+PyQt5 实现目录文件扫描与导出工具
python·qt·文件扫描
七夜zippoe1 天前
HTTP协议深度解析与实现:从请求响应到HTTP/3的完整指南
python·网络协议·http·quic·帧结构
好奇龙猫1 天前
【大学院-筆記試験練習:线性代数和数据结构(17)】
数据结构·学习·线性代数
你怎么知道我是队长1 天前
win11系统查看设备配置
android·java·javascript
倾国倾城的反派修仙者1 天前
鸿蒙开发——使用弹窗授权保存媒体库资源
开发语言·前端·华为·harmonyos
电化学仪器白超1 天前
③YT讨论
开发语言·python·单片机·嵌入式硬件
DevangLic1 天前
【确认是否安装了 C++ 工具】
android·java·c++
listhi5201 天前
基于MATLAB的平板小孔应力集中问题有限元分析程序
开发语言·matlab
b2077211 天前
Flutter for OpenHarmony 身体健康状况记录App实战 - 数据导出实现
python·flutter·harmonyos