Java--String类查找方法

在Java中,String类提供了多种用于查找字符串中特定子串的方法。下面列出了一些常用的方法,并给出示例代码:

1. indexOf(String str)

该方法返回指定子字符串str在此字符串中第一次出现处的索引,如果未找到该子字符串,则返回-1。

复制代码
String str = "Hello, World!";  
int index = str.indexOf("World");  
System.out.println("Found at index: " + index); // 输出: Found at index: 7

2. indexOf(String str, int fromIndex)

从指定的索引fromIndex处开始查找,返回指定子字符串str第一次出现处的索引。

复制代码
String str = "Hello, World! Welcome to Java.";  
int index = str.indexOf("World", 7); // 从索引7开始查找  
System.out.println("Found at index: " + index); // 输出: Found at index: 7

3. lastIndexOf(String str)

返回指定子字符串str在此字符串中最后一次出现处的索引,如果未找到则返回-1。

复制代码
String str = "Java is fun, Java is powerful.";  
int index = str.lastIndexOf("Java");  
System.out.println("Last found at index: " + index); // 输出: Last found at index: 20

4. lastIndexOf(String str, int fromIndex)

从指定的索引fromIndex处开始向后搜索,返回指定子字符串str最后一次出现处的索引。

复制代码
String str = "Java is fun, Java is powerful.";  
int index = str.lastIndexOf("Java", 10); // 从索引10向前查找  
System.out.println("Last found at index: " + index); // 输出: Last found at index: 0

5. contains(CharSequence s)

检查此字符串是否包含指定的子字符串(CharSequence)。如果包含,则返回true;否则返回false

复制代码
String str = "Hello, World!";  
boolean contains = str.contains("World");  
System.out.println("Contains 'World'? " + contains); // 输出: Contains 'World'? true

6. startsWith(String prefix)

测试此字符串是否以指定的前缀开始。

复制代码
String str = "Hello, World!";  
boolean startsWith = str.startsWith("Hello");  
System.out.println("Starts with 'Hello'? " + startsWith); // 输出: Starts with 'Hello'? true

7. endsWith(String suffix)

测试此字符串是否以指定的后缀结束。

复制代码
String str = "Hello, World!";  
boolean endsWith = str.endsWith("World!");  
System.out.println("Ends with 'World!'? " + endsWith); // 输出: Ends with 'World!'? true

这些方法都是String类中用于查找和检查子字符串的非常有用的工具。

双引号赋值:字符串常量池

boolean equals

比较两个字符串

String trim

去除字符的空格

posted @   curry库-04049  阅读(176)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示