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

}

}

}

相关推荐
chase。几秒前
【学习笔记】从经典算法到通用神经运动规划器
笔记·学习·算法
2301_810154551 分钟前
CVE-2019-6341 漏洞复现
java·开发语言
GuokLiu1 分钟前
260331-OpenWebUI统计所有Chat的对话字符个数
python
哈伦20192 分钟前
Python 生成随机数
python·机器学习·pandas
zzwq.5 分钟前
魔法方法 __init__ 与 __new__ 的区别与使用场景
python
SimonKing5 分钟前
IDEA 2026.1重磅发布:AI智能体全面开放,编程进入“万能插座”时代
java·后端·程序员
chushiyunen7 分钟前
langchain的流式事件监听astream_event()、todo运行机制
java·数据库·langchain
老虎06279 分钟前
数据结构09(Java)-- 二分查找模板
java·开发语言·数据结构
蓝天星空10 分钟前
C#中for循环和foreach循环的区别
开发语言·c#