char charAt(int index) - 用于返回参数指定下标位置的字符。
int length() - 用于返回当前字符串的长度。
public class TestStringCharAt {
public static void main(String[] args) {
//使用无参的构造方法来构造对象
String s1 = new String();
//获取String的长度
int len = s1.length();
System.out.println("len = " + len); //len = 0
System.out.println("--------------------------------");
//使用有参的构造方法来构造对象
String s2 = new String("hello");
len = s2.length();
System.out.println("len = " + len); //len = 5
//使用charAt()方法来获取里面的单个字符
//char cv = s2.charAt(-1); 产生字符串下标越界异常
char cv = s2.charAt(0);
System.out.println("cv = " + cv); //h
cv = s2.charAt(4);
System.out.println("cv = " + cv); //o
for(int i = 0; i < s2.length(); i++){
System.out.println(s2.charAt(i));
}
}
}
int length() - 用于返回当前字符串的长度。
public class TestStringCharAt {
public static void main(String[] args) {
//使用无参的构造方法来构造对象
String s1 = new String();
//获取String的长度
int len = s1.length();
System.out.println("len = " + len); //len = 0
System.out.println("--------------------------------");
//使用有参的构造方法来构造对象
String s2 = new String("hello");
len = s2.length();
System.out.println("len = " + len); //len = 5
//使用charAt()方法来获取里面的单个字符
//char cv = s2.charAt(-1); 产生字符串下标越界异常
char cv = s2.charAt(0);
System.out.println("cv = " + cv); //h
cv = s2.charAt(4);
System.out.println("cv = " + cv); //o
System.out.println("--------------------------------");
for(int i = 0; i < s2.length(); i++){
System.out.println(s2.charAt(i));
}
}
}