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

}

}

}

相关推荐
skywalk816334 分钟前
LTX-2 是一个基于 Transformer 的视频生成模型,能够根据文本描述生成高质量视频
python·深度学习·transformer
不懒不懒41 分钟前
【Python办公自动化进阶指南:系统交互与网页操作实战】
开发语言·python·交互
会周易的程序员41 分钟前
cNetgate插件架构设计详解 动态库 脚本二开lua, python, javascript
javascript·c++·python·物联网·lua·iot
普通网友43 分钟前
C++与Rust交互编程
开发语言·c++·算法
游乐码1 小时前
c#静态类和静态构造函数
开发语言·c#
小杨互联网1 小时前
项目CyberScan Pro jar软件安全成分分析插件
java·jar·软件成分分析·jar安全分析
小雨中_1 小时前
3.7 GSPO:Group Sequence Policy Optimization(组序列策略优化)
人工智能·python·深度学习·机器学习·自然语言处理
组合缺一1 小时前
Java 版 Claude Code CLI 来了!(国产开源项目)Solon Code CLI 发布
java·ai·开源·llm·solon·cli·claudecode
StandbyTime1 小时前
C语言学习-菜鸟教程C经典100例-练习79
c语言
散峰而望1 小时前
【算法竞赛】堆和 priority_queue
开发语言·数据结构·c++·算法·贪心算法·动态规划·推荐算法