一、字符串包含方法介紹
Java中的String類提供了多種方法來判斷一個字符串是否包含另一個字符串。這些方法包括:
- contains(CharSequence s)
- indexOf(String str)
- lastIndexOf(String str)
- startsWith(String prefix)
- endsWith(String suffix)
- matches(String regex)
下面將對每個方法進行詳細介紹。
二、contains(CharSequence s)
該方法判斷字符串是否包含指定的字符序列,返回一個布爾值。
示例代碼:
String str = "hello world"; boolean result = str.contains("world"); System.out.println(result); // 輸出 true
這個例子中,字符串”hello world”包含字符串”world”,所以返回true。
三、indexOf(String str)
該方法返回指定字符串在此字符串中第一次出現處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
示例代碼:
String str = "hello world"; int index = str.indexOf("world"); System.out.println(index); // 輸出 6
這個例子中,字符串”world”第一次出現在”hello world”的第7個位置,但是由於計數從0開始,所以返回6。
四、lastIndexOf(String str)
該方法返回指定字符串在此字符串中最右邊出現處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
示例代碼:
String str = "hello world"; int index = str.lastIndexOf("l"); System.out.println(index); // 輸出 9
這個例子中,字符”l”最後出現在”hello world”的第10個位置,但是由於計數從0開始,所以返回9。
五、startsWith(String prefix)
該方法測試此字符串是否以指定的前綴開頭。
示例代碼:
String str = "hello world"; boolean result = str.startsWith("he"); System.out.println(result); // 輸出 true
這個例子中,字符串”hello world”以”he”開頭,所以返回true。
六、endsWith(String suffix)
該方法測試此字符串是否以指定的後綴結束。
示例代碼:
String str = "hello world"; boolean result = str.endsWith("ld"); System.out.println(result); // 輸出 true
這個例子中,字符串”hello world”以”ld”結尾,所以返回true。
七、matches(String regex)
該方法使用給定的正則表達式來測試字符串是否滿足某個模式,返回一個布爾值。
示例代碼:
String str = "hello world"; boolean result = str.matches(".*world.*"); System.out.println(result); // 輸出 true
這個例子中,正則表達式”.*world.*”表示匹配任何包含”world”的字符串,因此返回true。
八、總結
通過上述介紹,我們了解了Java String類的多種包含方法,可以根據具體的需求選擇合適的方法來判斷一個字符串是否包含另一個字符串。
原創文章,作者:NQGIY,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/330202.html