indexOf() 方法有以下四种形式:
public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int indexOf(int ch, int fromIndex): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexOf(String str, int fromIndex): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int indexOf(int ch ) 或 public int indexOf(int ch, int fromIndex) 或 int indexOf(String str) 或 int indexOf(String str, int fromIndex)
ch -- 字符。
fromIndex -- 开始搜索的索引位置。
str -- 要搜索的子字符串。
指定子字符串在字符串中第一次出现处的索引,从指定的索引开始。
package com.jiaoben;
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str = "This is jiaobenzhijia";
// 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' = 13