今天來小結一下indexOf()方法的幾種API
首選自定義一個字符串(生活就像一盒巧克力,你永遠不會知道你要拿起的是哪一個——《阿甘正傳》)
String str= "life was like a box of chocolates you never know what you are gonna get";
1.indexOf(String str)
說明:從前往后查找指定的字符串,返回在自定義字符串中第一次出現的位置(返回索引值,從0開始)
如果自定義字符串中不包含指定的字符串,則返回-1
System.out.println(fileName.indexOf("e")); //3
System.out.println(fileName.indexOf("1")); //-1
2.indexOf(String str, int fromIndex)
說明:從指定位置(索引值)開始,往后查找指定字符串第一次出現的位置,返回索引值
注意:包括當前的指定位置,如果指定索引為3,那么即從life中的e(包括e)開始往后查找
System.out.println(fileName.indexOf("e", 4)); //12
3.lastIndexOf(String str)
說明:從前往后,查找指定字符串最后出現的位置(索引值)
System.out.println(fileName.lastIndexOf("e")); //69