Java.lang.String.indexOf() 方法
描述
java.lang.String.indexOf(int ch, int fromIndex) 方法返回此字符串中第一次出现指定字符的索引,从指定索引开始搜索。
如果值 ch 的字符出现在此 String 对象表示的字符序列中,且其索引不小于 fromIndex,则返回第一个此类出现的索引。
声明
以下是 java.lang.String.indexOf() 方法的声明。
public int indexOf(int ch, int fromIndex)
参数
ch − 这是一个字符(Unicode 代码点)。
fromIndex − 这是开始搜索的索引。
返回值
该方法返回该对象表示的字符序列中大于等于fromIndex的字符第一次出现的索引,如果没有出现则返回-1。
异常
NA
示例
下面的例子展示了 java.lang.String.indexOf() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str = "This is tutorialspoint";
// returns positive value as character is located
System.out.println("index of letter 't' = "
+ str.indexOf('t', 14));
// returns positive value as character is located
System.out.println("index of letter 's' = "
+ str.indexOf('s', 10));
// returns -1 as character is not in the string
System.out.println("index of letter 'e' = "
+ str.indexOf('e', 5));
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
index of letter 't' = 21 index of letter 's' = 16 index of letter 'e' = -1

