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

}

}

}

相关推荐
2401_88303546几秒前
持续集成/持续部署(CI/CD) for Python
jvm·数据库·python
JobDocLS1 分钟前
rknn3588的用法
python
郝学胜-神的一滴1 分钟前
深度学习框架新纪元:PyTorch核心原理与工程实践全解析
人工智能·pytorch·python·深度学习·机器学习
焦糖玛奇朵婷2 分钟前
盲盒抽卡机小程序搭建,探索卡牌市场
大数据·开发语言·程序人生·小程序·软件需求
liulilittle2 分钟前
C++实现广播地址计算
开发语言·c++
叶子2024222 分钟前
轻松的当下,迷茫的未来
python
智算菩萨3 分钟前
从零到精通:用 ChatGPT 5.4 解锁 Python 编程的无限可能——原理、技巧与工程实践全攻略
python·gpt·ai·chatgpt·ai编程
chushiyunen5 分钟前
pycharm实现skills示例
windows·python·pycharm
2501_941982055 分钟前
Java 实现企业微信外部群机器人:自动化消息交互
开发语言·python
学习永无止境@5 分钟前
Vivado FPGA输入时钟约束
开发语言·fpga开发·fpga