java.lang.String.indexOf(int ch, int fromIndex) 方法返回此字符串指定字符第一次出现处的索引,从开始搜索指定的索引处。
如果发生在由索引不超过fromIndex
在这个String对象表示的字符序列值ch
字符,那么返回第一个匹配项的索引。
声明
以下是java.lang.String.indexOf()
方法声明
public int indexOf(int ch, int fromIndex)
参数
ch
— 这是一个字符(Unicode代码点)。fromIndex
— 这是从索引开始搜索。
返回值
此方法返回字符在此对象大于或等于fromIndex
表示的字符序列中第一次出现的索引,或如果该字符未找到返回 -1
。
例子
下面的例子显示java.lang.String.indexOf()
方法的使用。
package com.yiibai;
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str = "This is yiibai tutorials";
// 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' = 15
index of letter 's' = 23
index of letter 'e' = -1