Java String类的常用方法(字符串查找)

No. 1 方法名称 类型 描述

1      public boolean contains(String str) 普通     判断指定内容是否存在

2 public int indexOf(String str) 普通 右前向后查找指定字符串位置,如果超找到了则返回(第一个字母)位置索引,如果找不到返回-1

3 public int indexOf(String str,int fromIndex) 普通 由指定位置从前向后查找指定字符串的位置,找不到返回-1

4 public int lastIndexOf(String str) 普通 由后向前查找字符串位置,找不到返回-1

5 public int lastIndexOf(String str,int fromIndex) 普通 从指定位置由后向前查找字符串位置,找不到返回-1

6 public boolean startsWith(String prefix) 普通 判断是否以指定的字符开头

7 public boolean startsWith(String prefix,int toffset) 普通 从指定位置开始判断是否以指定的字符开头

8 public boolean endWith(String suffix) 普通 判断是否以指定的字符串结尾

public class Demo {
public static void main(String[] args) {
String str = “helloworld”;
System.out.println("“world"所在的索引:” + str.indexOf(“world”));
System.out.println(“第一个"l"所在的索引:” + str.indexOf(“l”));
System.out.println(“从索引是5开始超找"l"所在的位置:” + str.indexOf(“l”, 5));
}
}

====================================================

public class Demo {
public static void main(String[] args) {
String str = “helloworld”;
if (str.contains(“world”)) {
System.out.println(“查找成功”);
}
}
}

====================================================

public class Demo {
public static void main(String[] args) {
String str = “ @ @ h e l l o ∗ ∗ ∗ " ; S y s t e m . o u t . p r i n t l n ( " 是 否 以 @@hello***"; System.out.println("是否以 @@hello";System.out.println("开头:” + str.startsWith("$$"));
System.out.println(“在索引为2的位置是否为@:” + str.startsWith("@@", 2));
System.out.println(“是否以结尾:" + str.endsWith("”));
}
}

猜你喜欢

转载自blog.csdn.net/weixin_42041819/article/details/100176795
今日推荐