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

}

}

}

相关推荐
爱打代码的小林2 分钟前
用 PyTorch 实现 CBOW 模型
人工智能·pytorch·python
shejizuopin2 分钟前
基于SSM的高校旧书交易系统的设计与实现(毕业论文)
java·mysql·毕业设计·论文·ssm·毕业论文·高校旧书交易系统的设计与实现
Coding茶水间5 分钟前
基于深度学习的花朵识别系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
开发语言·人工智能·深度学习·yolo·目标检测·机器学习
修己xj7 分钟前
SpringBoot解析.mdb文件实战指南
java·spring boot·后端
中二病码农不会遇见C++学姐9 分钟前
.env 文件是干啥的?为什么不能提交到 Git?
git·学习
近津薪荼11 分钟前
递归专题(3)——反转链表
数据结构·c++·学习·算法·链表
曲幽12 分钟前
FastAPI定时任务全攻略:从入门到避开多进程的坑
python·fastapi·web·async·sqlalchemy·lock·apscheduler·works
逢城戏元宇宙15 分钟前
区域文化IP‘逢城戏’进军元宇宙,AR盲盒带来哪些全新互动体
python
爱吃汽的小橘16 分钟前
揭秘802.15.4:物联网通信基石
网络·学习
I'mChloe18 分钟前
机器学习核心分支:深入解析监督学习
人工智能·学习·机器学习