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 分钟前
首页地图功能分析
java
段ヤシ.7 分钟前
回顾Java知识点,面试题汇总Day10:日期类、IO流(持续更新)
java·序列化·反序列化·日期类·i/o流
罗超驿10 分钟前
13.JavaScript 新手入门指南:语法、变量、流程控制全解析
开发语言·javascript
yingjie11015 分钟前
Scanpy vs Seurat 深度对比:Python 与 R 的单细胞分析框架谁更强?
开发语言·python·r语言·生物信息学·单细胞转录组·seurat·scanpy
程序大视界34 分钟前
【C++ 从基础到项目实战】C++(六):拷贝控制——浅拷贝与深拷贝,兼谈智能指针
开发语言·c++·cpp
luck_bor36 分钟前
IO流知识点笔记
java·开发语言·笔记
包子BI大数据39 分钟前
3.openclaw小龙虾简单版安装教程
人工智能·python·ai
程序大视界41 分钟前
【Python系列课程】Pandas(四):数据统计与排序——describe、sort_values、sample
开发语言·python·pandas
KWTXX1 小时前
使用matlab官网的skills调用claude-待完成
开发语言·matlab
XGeFei1 小时前
【Fastapi学习笔记(4)】—— JsonScheme与数据验证、错误响应格式、正则表达式
学习·fastapi