String的用法——判斷功能

package cn.itcast_03;
/*code

  • String的判斷功能:
  • 1.boolean equals(Object obj):字符串的內容是否相同,區分大小寫
  • 2.boolean equalsIgnoreCase(String str):比較字符串的內容是否相同,忽略大小寫
  • 3.boolean contains(String str):判斷大字符串中是否包含小字符串
  • 4.boolean startsWith(String str):判斷字符串是否以某個指定的字符串開始
  • 5.boolean endsWith(String str):判斷字符串是否以摸個指定的字符串結尾
  • 6.boolean isEmpty():判斷字符串是否爲空
  • 注意:
  • 字符串爲空和字符串對象爲空不同。
  • String s = "";字符串爲空
  • String s = null;字符串對象爲空
  • */

public class StringDemo {對象

public static void main(String[] args) {
    //建立對象
    String s1 = "helloworld";
    String s2 = "helloworld";
    String s3 = "HelloWorld";
    String s4 = "hell";
    
    //boolean equals(Object obj):字符串的內容是否相同,區分大小寫
    System.out.println("equals:" + s1.equals(s2));//true
    System.out.println("equals:" + s1.equals(s3));//false
    System.out.println("------------------------------------------------");
    
    //boolean equalsIgnoreCase(String str):比較字符串的內容是否相同,忽略大小寫
    System.out.println("equalsIgnoreCase:" + s1.equalsIgnoreCase(s2));//true
    System.out.println("equalsIgnoreCase:" + s1.equalsIgnoreCase(s3));//true
    System.out.println("------------------------------------------------");
    
    //boolean contains(String str):判斷大字符串中是否包含小字符串
    System.out.println("contains:" + s1.contains("hell"));//true
    System.out.println("contains:" + s1.contains("hw"));//false,字符必須是連在一塊兒的
    System.out.println("contains:" + s1.contains("owo"));//true
    System.out.println("contains:" + s1.contains(s4));//true
    System.out.println("------------------------------------------------");
    
    //boolean startsWith(String str):判斷字符串是否以某個指定的字符串開始
    System.out.println("startsWith:" + s1.startsWith("h"));//true
    System.out.println("startsWith:" + s1.startsWith(s4));//true
    System.out.println("startsWith:" + s1.startsWith("world"));//false
    System.out.println("------------------------------------------------");
    
    //boolean endsWith(String str):判斷字符串是否以摸個指定的字符串結尾
    System.out.println("endsWith:" + s1.endsWith("h"));//false
    System.out.println("endsWith:" + s1.endsWith(s4));//false
    System.out.println("endsWith:" + s1.endsWith("world"));//true
    System.out.println("------------------------------------------------");
    
    //boolean isEmpty():判斷字符串是否爲空
    System.out.println("isEmpty:" + s1.isEmpty());//false
    
    String s5 = "";
    String s6 = null;
    System.out.println("isEmpty:" + s5.isEmpty());//true
    //對象都不存在,因此不能調用方法
    System.out.println("isEmpty:" + s6.isEmpty());//NullPointerException
    
}

}字符串

相關文章
相關標籤/搜索