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

}

}

}

相关推荐
绝世唐门三哥3 分钟前
使用Intersection Observer js实现超出视口固定底部按钮
开发语言·前端·javascript
李拾叁的摸鱼日常3 分钟前
Spring 框架中 RequestContextHolder 深度解析
java·架构
TG:@yunlaoda360 云老大10 分钟前
腾讯云国际站代理商TACO Kit有什么优势呢?
学习·云计算·腾讯云
Ayu阿予11 分钟前
C++从源文件到可执行文件的过程
开发语言·c++
C++业余爱好者12 分钟前
JVM优化入门指南:JVM垃圾收集器(GC)介绍
java·开发语言·jvm
福尔摩斯张13 分钟前
基于C++的UDP网络通信系统设计与实现
linux·c语言·开发语言·网络·c++·tcp/ip·udp
dhdjjsjs15 分钟前
Day34 PythonStudy
python
Trouvaille ~18 分钟前
【Java篇】基石与蓝图::Object 类与抽象类的双重奏
java·开发语言·javase·抽象类·类与对象·基础入门·object类
hkNaruto18 分钟前
【规范】Linux平台C/C++程序版本发布调试规范手册 兼容银河麒麟
linux·c语言·c++
卜锦元19 分钟前
Golang中make()和new()的区别与作用?
开发语言·后端·golang