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 &apost&apos = "
+ str.indexOf(&apost&apos, 14))
// returns positive value as character is located
System.out.println("index of letter &aposs&apos = "
+ str.indexOf(&aposs&apos, 10))
// returns -1 as character is not in the string
System.out.println("index of letter &apose&apos = "
+ str.indexOf(&apose&apos, 5))
}
}
让我们来编译和运行上面的程序,这将产生以下结果:
index of letter &apost&apos = 15
index of letter &aposs&apos = 23
index of letter &apose&apos = -1