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
去除字符的空格
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构