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

}

}

}

相关推荐
happylifetree11 小时前
Python09:核心语法-数据存储与运算-字面量
python
落魄实习生11 小时前
Agent Scope Java 2.x 系列【7】工具使用
java·开发语言·ai
心之语歌11 小时前
Tkinter 画布基本梳理
运维·服务器·python
旺仔学长 哈哈11 小时前
springboot钓鱼爱好者交流平台APP设计与实现
java·spring boot·mysql·充电桩管理系统
茉莉玫瑰花茶12 小时前
GO [ 方法 ]
开发语言·后端·golang
Wx-bishekaifayuan12 小时前
django个性化旅游路线推荐平台49005-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
狗凯之家源码网12 小时前
微博图床 PHP 系统搭建与实战应用指南
android·开发语言·php
小白快快跑哦13 小时前
python-字符串全解(六):正则表达式-量词
python·正则表达式·字符串
自强的小白13 小时前
核心功能(Service接口)
java·mybatis