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

}

}

}

相关推荐
justjinji几秒前
PHP函数如何识别PCI设备厂商ID_PHP获取扩展卡硬件标识【说明】
jvm·数据库·python
2201_761040592 分钟前
怎么监控MongoDB副本集的复制缓冲区积压_复制流速率评估
jvm·数据库·python
2402_854808373 分钟前
Layui tab选项卡如何动态根据ID值进行程序化切换
jvm·数据库·python
m0_377618233 分钟前
mysql如何设置字段为自动递增_使用alter table添加auto increment
jvm·数据库·python
kronos.荒3 分钟前
N皇后问题(python)
python·回溯
Wyz201210244 分钟前
Navicat导入HTML网页报错怎么跳过_忽略错误记录高级选项
jvm·数据库·python
星幻元宇VR4 分钟前
VR流动行走平台|让虚拟体验真正“走起来”
科技·学习·安全·vr·虚拟现实
小江的记录本5 分钟前
【网络安全】《网络安全三大加密算法结构化知识体系》
java·前端·后端·python·安全·spring·web安全
InfinteJustice6 分钟前
CSS Grid布局如何实现响应式卡片网格_结合媒体查询调整列数
jvm·数据库·python
2301_813599556 分钟前
HTML函数开发用金属机身笔记本散热更好吗_材质对温控影响【指南】
jvm·数据库·python