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

}

}

}

相关推荐
t_hj13 分钟前
大模型微调
人工智能·python·深度学习
码农老李21 分钟前
openEuler2403服务器版 原生官方镜像和飞腾定制镜像
开发语言·php
charlie11451419144 分钟前
现代Qt开发教程(新手篇)2.3——QImage、QPixmap、QIcon 图像处理基础
开发语言·图像处理·qt
范范@1 小时前
python基础-函数
开发语言·python
2301_803934611 小时前
MySQL 字段类型选择规范指南
jvm·数据库·python
Bechamz1 小时前
大数据开发学习Day36
大数据·学习
特种加菲猫1 小时前
从零开始手撕AVL树:详解插入、平衡因子更新与四种旋转
开发语言·c++
oddsand11 小时前
Redis网络模型
java·数据库·redis
皮卡祺q2 小时前
【redies0-导论】分布式系统的演进-引进redis原因
java·数据库·redis
roman_日积跬步-终至千里2 小时前
如何分析复杂架构:一套真正能落地的方法
java·开发语言·架构