字符串查找
| 方法名称{类型} | 描述 |
|---|---|
| public boolean contains(String s){普通方法} | 判断子字符串是否存在 |
| public int indexOf(String str){普通方法} | 从头查找指定字符串的位置,找不到就返回-1 |
| public int indexOf(String str,int fromindex){普通方法} | 从指定位置查找指定字符串的位置 |
| public int lastIndexOf(String str){普通方法} | 由后向前查找指定字符串的位置 |
| public int lastIndexOf(String str,int fromIndex){普通方法} | 从指定位置 由后向前查找指定字符串的位置 |
| public boolean startsWith(String prefix){普通方法} | 判断是否以指定的字符串开头 |
| public boolean startsWith(String prefix,int toffset){普通方法} | 由指定位置判断是否以指定的字符串开头 |
| public boolean endsWith(Striing suffix){普通方法} | 判断是否以指定的字符串结尾 |
范例:查找字符串是否存在、使用indexOf()方法判断、使用lastIndexOf()查找、判断是否以指定的字符串开头或结尾
public class StringDemo151 {
public static void main(String[] args) {
String str="www.baidu.com";
System.out.println(str.contains("baidu"));
System.out.println(str.contains("tengxun"));
System.out.println(str.indexOf("baidu"));
if(str.indexOf("baidu")!=-1) {
System.out.println("要查询的字符串存在");
}
System.out.println(str.indexOf("alibaba"));
System.out.println(str.lastIndexOf("c")+" 从后往前查找,返回了第一个查找到的索引位置");
System.out.println(str.startsWith("www")+"开头判断");
System.out.println(str.startsWith(".",3)+" 从指定索引之后进行开头判断");
System.out.println(str.endsWith("com")+" 结尾判断");
}
}
true
false
4
要查询的字符串存在
-1
10 从后往前查找,返回了第一个查找到的索引位置
true开头判断
true 从指定索引之后进行开头判断
true 结尾判断
使用indexOf0方法实现字符串索引查找,如果可以找到指定内容就会返回索引数据(返回起始索引);如果没有找到子字符串会返回-1;
本文详细介绍了字符串操作中的核心方法,包括查找子字符串、判断字符串是否包含特定子串、确定字符串的开始和结束等实用技巧,通过具体示例展示了如何使用Java中的String类方法,如contains、indexOf、lastIndexOf、startsWith和endsWith。
2698

被折叠的 条评论
为什么被折叠?



