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

}

}

}

相关推荐
Wyz20121024几秒前
如何在 React 中正确绑定 onClick 事件避免字符串赋值错误
jvm·数据库·python
itman3017 分钟前
C语言printf输出格式:%d %f %s等用法详解
c语言·字符串·printf·格式化输出·整数
zhangrelay9 分钟前
智能时代机器人工程师・云原生 + 大模型 + 智能体 全栈成长计划(2026 版)
笔记·学习
m0_377618239 分钟前
如何在 Node.js 服务器间正确配置 CORS 实现跨子域资源访问
jvm·数据库·python
qq_1898070310 分钟前
如何在 Django ListView 中正确过滤当前用户的照片数据
jvm·数据库·python
U盘失踪了10 分钟前
go 切片
golang
老约家的可汗10 分钟前
搜索二叉树的概念及使用
java·开发语言
m0_3776182311 分钟前
Go语言如何用systemd_Go语言systemd服务管理教程【总结】
jvm·数据库·python
不知名的老吴13 分钟前
R语言4.3.0安装包百度网盘中文版下载与详细安装指南
开发语言·r语言
棉猴15 分钟前
python海龟绘图之计算夹角towards()
开发语言·python·turtle·海龟绘图·towards