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 分钟前
增强型大模型代理
python
小李云雾3 分钟前
FastAPI 后端开发:文件上传 + 表单提交
开发语言·python·lua·postman·fastapi
Legend NO244 分钟前
数据资产评估风险识别、分析与管控体系建设
大数据·人工智能·python
高斯林.神犇5 分钟前
四、依赖注入.spring
java·后端·spring
hero.fei8 分钟前
在springboot中使用Resilience4j
java·spring boot·后端
llm大模型算法工程师weng9 分钟前
Python敏感词检测方案详解
开发语言·python·c#
AI_零食9 分钟前
Flutter 框架跨平台鸿蒙开发 - 社交断舍离应用
运维·服务器·学习·flutter·游戏·开源·harmonyos
沐苏瑶9 分钟前
Java算法之排序
java·算法·排序算法
fengci.10 分钟前
php反序列化(复习)(第二章)
android·开发语言·学习·php
世人万千丶10 分钟前
Flutter 框架跨平台鸿蒙开发 - 感恩杀手应用
学习·flutter·开源·harmonyos·鸿蒙