String类的判断功能举例测试
在API中有很多判断功能,这里我取几个我们常用的来讲解下
boolean equals (Object obj)
判断字符串内容是否相同,区分大小写
class test{
public static void main(String[] args){
String s1 = "helloworld";
String s2 = "helloworld";
String s3 = "HelloWorld";
System.out.println("equals:"+s1.equals(s2));
System.out.println("equals:"+s1.equals(s3));
//第一个输出结果:equals:true
//第二个输出结果:equals:false
}
}
boolean equalsIgnoreCase(String str)
比较字符串的内容是否相同,忽略大小写
class test{
public static void main(String[] args){
String s1 = "helloworld";
String s2 = "helloworld";
String s3 = "HelloWorld";
System.out.println("equalsIgnoreCase:"+s1.equalsIgnoreCase(s2));
System.out.println("equalsIgnoreCase:"+s1.equalsIgnoreCase(s3));
//第一个输出结果:equalsIgnoreCase:true
//第二个输出结果:equalsIgnoreCase:true
}
}
boolean contains(String str)
判断大字符串中是否包含小字符串
class test{
public static void main(String[] args){
String s1 = "helloworld";
System.out.println("contains:"+s1.contains("hello"));
System.out.println("contians:"+s1.contains("w"));
//第一个输出结果:contains:true
//第二个输出结果:contains:true
}
}
boolean startsWith(String str)
判断字符串是否以某个指定的字符串开头
class test{
public static void main(String[] args){
String s1 = "helloworld";
System.out.println("startsWith:"+s1.startsWith("h"));
System.out.println("startsWith:"+s1.startsWith("hel"));
System.out.println("startsWith:"+s1.startsWith("wor"));
//第一个输出结果:startsWith:true
//第二个输出结果:startsWith:true
//第二个输出结果:startsWith:false
}
}
boolean endsWith(String str)
判断字符串是否以某个指定的字符串结尾
class test{
public static void main(String[] args){
String s1 = "helloworld";
System.out.println("endsWith:"+s1.endsWith("d"));
System.out.println("endsWith:"+s1.endsWith("ld"));
System.out.println("endsWith:"+s1.endsWith("worl"));
//第一个输出结果:endsWith:true
//第二个输出结果:endsWith:true
//第二个输出结果:endsWith:false
}
}
boolean isEmpty()
判断字符串是否为空
class test{
public static void main(String[] args){
String s1 = "helloworld";
String s2 = "";
System.out.println("isEmpty:"+s1.isEmpty());
System.out.println("isEmpty:"+s2.isEmpty());
//第一个输出结果:isEmpty:false
//第二个输出结果:isEmpty:true
}
}