比较String对象
有两种方法比较String对象:
1使用String类覆盖的Object类的equals方法,返回true如果两个String对象字符串相同,否则返回false
if (string1.equals(string2))
2使用compareTo方法,compareTo方法把string按照ASCII表的顺序逐字符比较,ASCII表中数字顺序先于大写字母,大写字母先于小写字母。
compareTo比较时如果两个字符串的字符不相同,返回第一个不相同字符ASCII差值,如果字符相同但是长度不同返回长度差值,如果字符和长度相同返回0.
package standardClasses;
public class ComparisonOfString {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "HOT";
String s2 = "HOTEL";
String s3 = "GOT";
String s4 = "HOT";
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
}
}
如果使用==比较string会判断两个指针是否指代同一字符串对象,而非比较字符串的实际内容。
String s1 = "abc";
String s2 = "abc";
if (s1 == s2) {
}
会返回true,因为为了节约内存,介于String对象不可修改的性质,对于同一字符串内容java只会创建一个字符串对象,因而s1和s2指代其实相同
String s1 = "abc";
String s2 = new String("abc");
if (s1 == s2)
会返回false,因为s2此时是新建的字符串对象,和s1指代不同。
因此,尽量避免使用==比较string
其他String方法:
int length()
返回String长度
String substring(int startIndex)
返回该String一部分的新字符串,子字符串从startIndex位置字符到字符串末尾。如果startIndex为负或者大于String长度会抛出异常IndexOutOfBoundsException
String substring(int startIndex, int endIndex)
返回String一部分的子字符串,子字符串从startIndex开始,到endIndex - 1. (可以理解startIndex是第一个要截的字符,endIndex是第一个不要截的字符)。如果startIndex小于0,endIndex大于String长度,或者startIndex大于endIndex会抛出IndexOutOfBoundsException
int indexOf (String, str)
返回该字符串中第一次出现str的索引,如果不存在返回-1。如果str为null返回NullPointerException
实例程序
System.out.println("unhappy".substring(2));
System.out.println("cold".substring(4));
try {
System.out.println("cold".substring(5));
} catch (StringIndexOutOfBoundsException exception) {
System.out.println("Index out of bounds");
}
System.out.println("strawberry".substring(5, 7));
String c = "crayfish";
System.out.println(c.substring(4, 8));
try {
System.out.println(c.substring(4, 9));
System.out.println(c.substring(5, 4));
} catch (StringIndexOutOfBoundsException exception) {
System.out.println("Index out of bounds");
}
String s = "funnyfarm";
System.out.println(s.indexOf("farm"));
System.out.println(s.indexOf("farmer"));
System.out.println(s.length());
try……catch语句AP完全不会涉及,这里是我自己为了显示结果加上去的