學習筆記,僅供參考
String類
String類的判斷功能
equals方法
public boolean equals(Object anObject)
將此字符串與指定的對象比較。當且僅當該參數不爲null,並且是與此對象表示相同字符序列的 String 對象時,結果才爲 true。
-
參數
- anObject - 與此 String 進行比較的對象。
-
返回
- 如果給定對象表示的 String 與此 String 相等,則返回 true,否則返回 false。
equalsIgnoreCase方法
public boolean equalsIgnoreCase(String anotherString)
將此 String 與另一個 String 比較,不考慮大小寫。如果兩個字符串的長度相同,並且其中的相應字符都相等(忽略大小寫),則認爲這兩個字符串是相等的。
-
在忽略大小寫的情況下,如果下列至少一項爲 true,則認爲 c1 和 c2 這兩個字符相同。
-
這兩個字符相同(使用
==
運算符進行比較)。 -
對每個字符應用方法 Character.toUpperCase(char) 生成相同的結果。
-
對每個字符應用方法 Character.toLowerCase(char) 生成相同的結果。
-
-
參數
- anotherString - 與此 String 進行比較的 String。
-
返回
- 如果參數不爲 null,且這兩個 String 相等(忽略大小寫),則返回 true,否則返回 false。
contains方法
public boolean contains(CharSequence s)
當且僅當此字符串包含指定的 char 值序列時,返回 true。
-
參數
- s - 要搜索的序列
-
返回
- 如果此字符串包含 s,則返回 true,否則返回 false
startsWith方法
public boolean startsWith(String prefix, int toffset)
測試此字符串從指定索引開始的子字符串是否以指定前綴開始。
-
參數
- prefix - 前綴。
- toffset - 在此字符串中開始查找的位置。
-
返回
- 如果參數表示的字符序列是此對象從索引toffset 處開始的子字符串前綴,則返回 true,否則返回 false。如果 toffset 爲負或大於此 String 對象的長度,則結果爲 false,否則結果與以下表達式的結果相同:
this.substring(toffset).startsWith(prefix)
- 如果參數表示的字符序列是此對象從索引toffset 處開始的子字符串前綴,則返回 true,否則返回 false。如果 toffset 爲負或大於此 String 對象的長度,則結果爲 false,否則結果與以下表達式的結果相同:
endsWith方法
public boolean endsWith(String suffix)
測試此字符串是否以指定的後綴結束。
-
參數
- suffix - 後綴。
-
返回
- 如果參數表示的字符序列是此對象表示的字符序列的後綴,則返回 true,否則返回 false。注意,如果參數是空字符串,或者等於此 String 對象,則結果爲 true。
isEmpty方法
public boolean isEmpty()
當且僅當length()爲 0 時返回 true。
- 返回
- 如果 length() 爲 0,則返回 true,否則返回 false。
舉個例子
package com.guiyang.object;
public class Demo4_StringMethod {
public static void main(String[] args) {
String s1 = "xiaobai";
String s2 = "xiaobai";
String s3 = "XiaoBai";
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println("-----------------");
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3));
System.out.println("-----------------");
String s4 = "蚌埠市曹山路962號安徽財經大學";
String s5 = "蚌埠市";
String s6 = "財經大學";
System.out.println(s4.contains(s5));
System.out.println(s4.startsWith(s5));
System.out.println(s4.startsWith(s6));
System.out.println(s4.endsWith(s5));
System.out.println(s4.endsWith(s6));
System.out.println("-----------------");
String s7 = "xiaobai";
String s8 = "";
String s9 = null;
System.out.println(s7.isEmpty());
System.out.println(s8.isEmpty());
System.out.println(s9.isEmpty());
}
}
輸出:
true
false
-----------------
true
true
-----------------
true
true
false
false
true
-----------------
false
true
Exception in thread "main" java.lang.NullPointerException
at com.guiyang.object.Demo4_StringMethod.main(Demo4_StringMethod.java:38)
我們看到對null進行是否爲空的判斷時,報了一個空指針異常NullPointerException
,這是因爲null是空常量,不能調用任何的方法。