Java String charAt() 与 length() 方法
charAt() 方法
charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。
语句:
public char charAt(int index)
参数
- index -- 字符的索引。
返回值:返回指定索引处的字符。
charAt()方法实例
public class Test {
public static void main(String args[]) {
String s = "www.catroom.com.cn";
char result = s.charAt(6);
System.out.println(result);
}
}
以上程序执行结果为:
t
length() 方法
length() 方法用于返回字符串的长度。空字符串的长度返回 0。
语句:
public int length()
length()方法实例;
public class Test {
public static void main(String args[]) {
String Str1 = new String("www.catroom.com.cn");
String Str2 = new String("catroom" );
System.out.print("字符串 Str1 长度 :");
System.out.println(Str1.length());
System.out.print("字符串 Str2 长度 :");
System.out.println(Str2.length());
}
}
以上程序执行结果为:
字符串 Str1 长度 :20
字符串 Str2 长度 :7