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

}

}

}

相关推荐
saoys2 分钟前
Opencv 学习笔记:图像卷积操作(锐化核实战 + 数据类型避坑)
笔记·opencv·学习
查无此人byebye9 分钟前
实战DDPM扩散模型:MNIST手写数字生成+FID分数计算(完整可运行版)
人工智能·pytorch·python·深度学习·音视频
好家伙VCC15 分钟前
# 光计算驱动的编程范式革新:用Python实现光子神经网络模拟器在传统电子计算架构逼近物理极限的今天,**光计算**正
java·开发语言·python·神经网络
梵刹古音17 分钟前
【C++】 虚指针(vptr)与虚函数表(vtable)
开发语言·c++
Dxy123931021619 分钟前
Python使用正则提取字符串中的数字
python
来两个炸鸡腿20 分钟前
【Datawhale组队学习202602】Easy-Vibe task02 认识AI IDE工具
ide·人工智能·学习·大模型
yqj23423 分钟前
【无标题】
java·开发语言
Bin Watson29 分钟前
FOC学习记录(2):Clarke、Park、反 Clarke 和逆 Park 变换
学习
花果山总钻风32 分钟前
SQLAlchemy各种排序示例
后端·python·中间件