Java中charAt()和indexOf()之间的区别?

String类的 charAt() 方法返回指定索引处的char值。索引的范围是0到length()-1。序列的第一个char值在索引0处,下一个在索引1处,依此类推,与数组索引一样。

String类的indexOf(int ch,int fromIndex) 方法返回第一次出现的指定字符在此字符串中的索引,并从指定的索引开始搜索。
如果在此String对象表示的字符序列中出现的值为ch的字符的索引不小于fromIndex,则返回第一次出现的索引。

示例

public class CharAt_IndexOf_Example {
   public static void main(String args[]){
      String str = "This is nhooo";
      System.out.println("Index of letter 't' = "+ str.indexOf('t', 14));
      System.out.println("Letter at the index 8 is ::"+str.charAt(8));
   }
}

输出结果

Index of letter 't' = 21
Letter at the index 8 is ::t