indexOf 方法返回字符串中指定字符首次出现的索引。如果在字符串中找不到该字符,则返回 -1。
String str = "Search character";
/*
* The indexOf method only returns the
* index of the first occurrence of the character
*/
//will print 1, that is position 2 in the string
System.out.println( str.indexOf('e') );
//will print -1, as character z is not present in the string
System.out.println( str.indexOf('z') );
输出:
1
-1
默认的 indexOf 方法从索引 0 开始搜索字符。也可以用重载的 indexOf(char ch,int startIndex) 方法从指定位置开始搜索字符。
String str = "Search character";
/*
* this will start searching for a character 'e'
* from index 2 i.e. position 3 in the string
*/
//will print 14, that is position 15 in the string
System.out.println( str.indexOf('e', 2) );
输出:
14
同样,要搜索字符在字符串中最后一次出现的索引,可使用 lastIndexOf 方法。
String str = "Search character";
/*
* The lastIndexOf method searches the string
* backwards for a given character
*/
//this will print 14, i.e. position 15 in the string
System.out.println( str.lastIndexOf('e') );
/*
* you can also specify the index
* you want to start searching from
*/
/*
* this will print 1, because it will start searching
* for character 'e' from index 13 in the backward
* direction
*/
System.out.println( str.lastIndexOf('e', 13) );
输出:
14
1