提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、indexOf()方法
(1)indexOf()方法:用于获取指定字符在字符串第一次出现时的索引值
(2)indexOf()方法包括以下4个方法:
- indexOf(int t):返回指定字符在字符串中第一次出现的索引(位置),没有查到该字符时,则返回-1。
- indexOf(int t,int fromindex):返回从fromindex的位置开始查找到指定字符在字符串中第一次出现的位置,若该字符串不含有该字符,则返回-1。
- indexOf(String str):返回指定字符在字符串中第一次出现的位置,没有查到该字符时,则返回-1。
- indexOf(String str,int fromindex):返回从fromindex的位置开始查找到指定字符在字符串中第一次出现的位置,若该字符串不含有该字符,则返回-1。
例子:
@Test
public void test() {
String str = "Hello a12314abc";
//indexOf(int t):当参数为int型时,会先把该值根据ASCII字符转换为对应的字符再进行查找
System.out.println(str.indexOf(97));
//intdexOf(String str)
System.out.println(str.indexOf("a"));
//indexOf(int t, int fromindex)
System.out.println(str.indexOf(99, 2));
//intdexOf(String str)
System.out.println(str.indexOf("c", 3));
}
结果如下:
二、lastIndexOf()方法
(1)lastIndexOf()方法:用于获取指定字符在字符串中最后一次出现的索引值。
(2)lastIndexOf()一般包括以下4个方法:
- lastIndexOf(int ch): (该整型与ASICC字符中对应的字符相匹配)返回指定字符在字符串中最后一次出现的位置,若该字符串不包括此字符,则返回-1。
- lastIndexOf(String str): 返回指定字符在字符串中最后一次出现的位置,若该字符串不包括此字符,则返回-1。
- lastIndexOf(String str, int formIndex) :从后向前进行查找,返回指定字符在字符串中最后一次出现的位置,若该字符串不包括此字符,则返回-1。
- lastIndexOf(int ch int formIndex) :(该整型与ASICC字符中对应的字符相匹配)从后向前进行查找,返回指定字符在字符串中最后一次出现的位置,若该字符串不包括此字符,则返回-1。
如:
@Test
public void test02() {
String str = "Hello World12345aba.jpg";
System.out.println(str.lastIndexOf("."));
System.out.println(str.lastIndexOf(97));
System.out.println(str.lastIndexOf(".", 4));
System.out.println(str.lastIndexOf(".", 20));
System.out.println(str.lastIndexOf(97, 22));
}
结果如下:
三、substring()方法
(1)substring()方法:用于截取字符串。
(2)substring()包括以下2个方法:
- substring(int a,int b):表示从索引值为a的位置(包括)开始截取一直到索引值为b(不包括此位置的字符)的字符串。
- substring(int a):表示从从索引值为a的位置(包括)开始截取,直到该字符串的结尾。
例子:
@Test
public void test() {
String str = "Hello a12314abc";
//从索引值0开始截取到索引值为3(不包括)的那部分字符串
System.out.println(str.substring(0, 3));
//从索引值为3开始截取,一直到结尾
System.out.println(str.substring(3));
System.out.println(str.substring(str.indexOf("l") + 1));
}
结果如下:
四、split()方法
(1)split()方法:用于分割字符串。
(2)split()一般有以下2种方法:
- split(String t):表示依据字符t对字符串进行分割,存储在String数组当中。
- split(String t, int a):表示依据字符t对字符串进行分割,并限制分割数为a, 存储在String数组当中。
例子:
@Test
public void test() {
String str = "Hello a12314abc ss tst";
String[] split = str.split(" ");
for (String s : split) {
System.out.println(s);
}
//依据空格进行分割,并限制分割的数量为3段
String[] split1 = str.split(" ", 3);
for (String s1 : split1) {
System.out.println(s1);
}
}
结果如下: