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 小时前
8-8 WPS JS宏 正则表达式 字符组与任选
java·服务器·前端
Elastic 中国社区官方博客2 小时前
从向量到关键词:在 LangChain 中的 Elasticsearch 混合搜索
大数据·开发语言·数据库·elasticsearch·搜索引擎·ai·langchain
学编程的闹钟2 小时前
C语言GetLastError函数
c语言·开发语言·学习
一嘴一个橘子2 小时前
mybatis-plus 基于 service 接口的 crud
java
OPEN-Source2 小时前
给 Agent 安装技能:工具抽象、自动选工具与安全边界
人工智能·python·agent·rag·deepseek
梵刹古音2 小时前
【C++】多态
开发语言·c++
hello 早上好2 小时前
07_JVM 双亲委派机制
开发语言·jvm
ljxp12345682 小时前
高效删除链表重复节点
python
52Hz1182 小时前
力扣207.课程表、208.实现Trie(前缀树)
python·leetcode
Maguyusi2 小时前
go 批量生成c++和lua proto文件
c++·golang·lua·protobuf