Java是一種基於類和對象的編程語言,其擁有豐富的API庫,包括字符串(String)類。字符串類是Java中使用最頻繁的對象之一,其提供了許多實用的方法,這些方法可以幫助我們更好地操作字符串。在本文中,我們將介紹Java中的endsWith方法,它是字符串類中的一個方法,可以檢查字符串是否以指定的後綴結尾。
1. 介紹endsWith方法
在Java中,endsWith是一個字符串方法,其可以用於檢查一個字符串是否以指定的後綴結尾。該方法是一個布爾型方法,當字符串以指定的後綴結尾時返回true,否則返回false。
2. endsWith方法的用法
(1)startsWith方法基本用法
endsWith方法的基本用法非常簡單,以下是示例代碼:
public class Demo { public static void main(String[] args) { String str = "Hello World"; boolean isEndsWith = str.endsWith("World"); System.out.println("isEndsWith: " + isEndsWith); } }
通過上述代碼,我們可以得到以下輸出結果:
isEndsWith: true
該示例中,我們首先定義了一個名為str的字符串,接着使用endsWith方法檢查了該字符串是否以“World”結尾,並把方法的返回值存儲到isEndsWith變量中。最後,我們輸出了isEndsWith變量的值,該值為true,因為該字符串以“World”結尾。
(2)startsWith方法的忽略大小寫用法
endsWith方法還支持忽略大小寫進行比較,以下是示例代碼:
public class Demo { public static void main(String[] args) { String str = "Hello World"; boolean isEndsWith = str.endsWith("world"); System.out.println("isEndsWith: " + isEndsWith); } }
通過上述代碼,我們可以得到以下輸出結果:
isEndsWith: false
該示例中,我們同樣定義了一個名為str的字符串,接着使用endsWith方法檢查了該字符串是否以“world”結尾,並把方法的返回值存儲到isEndsWith變量中。最後,我們輸出了isEndsWith變量的值,該值為false,因為該字符串不以“world”結尾。需要注意的是,這裡忽略了字符串的大小寫,如果不進行忽略,方法則會返回false。
(3)endsWith方法的參數為空字符串
endsWith方法還可以接受一個空字符串作為參數,以下是示例代碼:
public class Demo { public static void main(String[] args) { String str1 = "Hello World"; boolean isEndsWith1 = str1.endsWith(""); System.out.println("isEndsWith1: " + isEndsWith1); String str2 = ""; boolean isEndsWith2 = str2.endsWith(""); System.out.println("isEndsWith2: " + isEndsWith2); } }
通過上述代碼,我們可以得到以下輸出結果:
isEndsWith1: true isEndsWith2: true
該示例中,我們定義了兩個字符串str1和str2,接着分別使用endsWith方法檢查了這兩個字符串是否以空字符串結尾,並把方法的返回值存儲到isEndsWith1和isEndsWith2變量中。最後,我們輸出了這兩個變量的值,結果均為true。
(4)endsWith方法的參數為null值
endsWith方法不接受null值作為參數,當使用null作為參數時,該方法會拋出NullPointerException。
public class Demo { public static void main(String[] args) { String str = "Hello World"; boolean isEndsWith = str.endsWith(null); System.out.println("isEndsWith: " + isEndsWith); } }
通過上述代碼,我們會得到以下異常信息:
Exception in thread "main" java.lang.NullPointerException at java.base/java.lang.String.endsWith(String.java:2029) at Demo.main(Demo.java:4)
該示例中,我們同樣定義了一個名為str的字符串,接着使用endsWith方法傳遞了null值作為參數,該方法拋出了NullPointerException 運行時異常,因為endsWith方法不接受null作為參數。
3. 小結
在本文中,我們介紹了Java中字符串類的endsWith方法,該方法可用於檢查一個字符串是否以指定的後綴結尾。我們通過示例代碼演示了endsWith方法的基本用法、忽略大小寫用法、參數為空字符串和參數為null值的用法,希望對Java開發者們有所幫助。
原創文章,作者:WNPY,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/138951.html