Java.lang.String.indexOf() 方法
描述
java.lang.String.indexOf(int ch) 方法返回该字符串中第一次出现指定字符的索引。
如果值 ch 的字符出现在此 String 对象表示的字符序列中,则返回第一个此类出现的索引(Unicode 代码单元)。
声明
以下是 java.lang.String.indexOf() 方法的声明。
public int indexOf(int ch)
参数
ch − 这是一个字符(Unicode 代码点)。
返回值
此方法返回此对象表示的字符序列中字符第一次出现的索引,如果该字符不出现,则返回-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 the index of occurrence of character s
System.out.println("index of letter 's' = "
+ str.indexOf('s'));
// returns -1 as character e is not in the string
System.out.println("index of letter 'e' = "
+ str.indexOf('e'));
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
index of letter 's' = 3 index of letter 'e' = -1

