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 tutorialspoint";
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP