AP计算机教程3-2:考试中的字符串方法
AP计算机科学考试只考察字符串的一小部分知识。所有的相关method也会在随卷的快速参考中列出,因此并不需要背诵记忆。推荐在练习备考时打印一份快速参考便于随时查对。
int length()返回字符串中的字符数,包含空格String substring(int from, int to)返回一个由当前字符串构造的新字符串。新字符串从当前字符串的from处开始,到to之前的字符为止。(如果不提供第二个to参数,新字符串将包括从from处开始到原字符串结束的部分。)int indexOf(String str)返回str在当前字符串的开始位置,如果无法找到则返回-1。int compareTo(String other)在当前字符串小于other时返回负值,两字符串等同时返回0,大于other时返回正值。如果两字符串前面有一部分相同,则对不同的第一位进行比较。boolean equals(String other)在当前字符串与other等同时返回true,否则返回false。该method由Object继承而来,但重写成为了判断字符串内容相等。
String还提供不少额外的method,可以查看官方文档。但单纯备考的话还是先将以上这五个method充分理解消化。
Java中的String是不变(immutable)的。所有对字符串进行的修改事实上都是返回新的String object。
0:00
What is the value of s1 after the following code executes?
String s1 = "Hi"; String s2 = s1.substring(0,1); String s3 = s2.toLowerCase();
Java中的字符串不变,
s1也未有被另赋新值。1
What is the value of s3 after the following code executes?
String s1 = "Hi"; String s2 = s1.substring(0,1); String s3 = s2.toLowerCase();
s2取到了s1的第一个字符,而s3是把s2变为小写。4
What is the value of pos after the following code executes?
String s1 = "abccba";
int pos = s1.indexOf("b");
Java的索引都从
0开始,而b第一次出现在位置1。2
What is the value of len after the following executes?
String s1 = "Miss you!"; int len = s1.length();
9个字符,长度为
9。3
What is the value of s2 after the following code executes?
String s1 = new String("hi there");
int pos = s1.indexOf("e");
String s2 = s1.substring(0,pos);
取到的部分是从开始到第一个
e之前。1
0 条评论