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

}

}

}

相关推荐
JeffDingAI40 分钟前
【Datawhale学习笔记】NLP初级分词技术
笔记·学习·自然语言处理
zh_xuan1 小时前
kotlin 尾随Lambda表达式函数的常用简写
开发语言·kotlin
码出财富8 小时前
SpringBoot 内置的 20 个高效工具类
java·spring boot·spring cloud·java-ee
沐知全栈开发8 小时前
Perl 数据库连接
开发语言
优雅的潮叭8 小时前
c++ 学习笔记之 shared_ptr
c++·笔记·学习
多米Domi0118 小时前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
我是小疯子668 小时前
Python变量赋值陷阱:浅拷贝VS深拷贝
java·服务器·数据库
freepopo8 小时前
天津商业空间设计:材质肌理里的温度与质感[特殊字符]
python·材质
am心8 小时前
学习笔记-用户下单
笔记·学习
森叶8 小时前
Java 比 Python 高性能的原因:重点在高并发方面
java·开发语言·python