String类的判断功能
程序示例
/*
String类的判断功能
boolean equals(Object obj)
boolean equalsIgnoreCase(String str)
boolean contains(String str)
boolean startsWith(String str)
boolean endsWith(String str)
boolean isEmpty()
*/
public class StringDemo6 {
public static void main(String[] args) {
String s1 = "helloworld";
String s2 = "Helloworld";
String s3 = "HelloWorld";
//boolean equals(Object obj) 比较字符串的内容是否相同 区分大小写
System.out.println(s1.equals(s2));//false
System.out.println(s1.equals(s3));//false
System.out.println("**************************");
//boolean equalsIgnoreCase(String str)
//比较字符串的内容是否相同,忽略大小写
System.out.println(s1.equalsIgnoreCase(s2));//true
System.out.println(s1.equalsIgnoreCase(s3));//true
System.out.println("**************************");
//boolean contains(String str)
//当且仅当此字符串包含指定的char值序列时才返回true。
//判断大的字符串中是否包含小的字符串,如果包含,返回true,反之false
//区分大小写
System.out.println(s1.contains("Hello"));//false
System.out.println(s1.contains("leo"));//false
System.out.println(s1.contains("hello"));//true
System.out.println("**************************");
//boolean startsWith(String str)
//测试此字符串是否以指定的前缀开头。
//区分大小写
System.out.println(s1.startsWith("hel"));//true
System.out.println(s1.startsWith("h"));//true
System.out.println(s1.startsWith("he"));//true
System.out.println(s1.startsWith("he34"));//false
System.out.println(s1.startsWith("H"));//false
System.out.println("**************************");
//boolean endsWith(String str)
//测试此字符串是否以指定的后缀结束。
//区分大小写
System.out.println(s1.endsWith("orld"));//true
System.out.println(s1.endsWith("orlD"));//false
System.out.println("**************************");
//boolean isEmpty() 判断字符串是否是空字符串
System.out.println(s1.isEmpty());//false
//今后可能会遇到两种情况
String s4 = "";//空字符串
String s5 = null;//地址值为null,连地址值都没有,连字符串都不算
System.out.println(s4==s5);//false
System.out.println(s4.isEmpty());//true
//那么我s4都能调用isEmpty()方法,那么我s5能调用吗?
//NullPointerException--空指针异常
// System.out.println(s5.isEmpty());
//今后还有可能会遇见这种情况
String s6 = "bigdata";
String s7 = null;
System.out.println(s6.equals(s7));//false
// System.out.println(s7.equals(s6));//报错,null调不了方法。
/*
字符串之间比较的要求,在不知道两个字符串变量的值的时候,为了防止
空指针异常,把变量放在后面
*/
//需求:将s6,s7与"hadoop"进行比较
// System.out.println(s6.equals("hadoop"));
// System.out.println(s7.equals("hadoop"));
/*
推荐写法:这样不会报错
*/
System.out.println("hadoop".equals(s6));
System.out.println("hadoop".equals(s7));
}
}