一、使用String的contains()
String類中的contains()方法是判斷一個字元串是否包含另一個字元串的最簡單的方法。其語法如下:
public boolean contains(CharSequence s)
其中,參數s可以是一個char或者String類型的字元串。
示例代碼:
String str1 = "hello world"; String str2 = "world"; if(str1.contains(str2)){ System.out.println("包含"); }else{ System.out.println("不包含"); }
在上面的示例中,str1包含字元串”world”,因此輸出結果為”包含”。
二、使用正則表達式
如果需要判斷是否包含多個不同的字元串或者字元串的匹配模式比較複雜,可以使用正則表達式。Java的正則表達式語法和其他語言的正則表達式語法類似,具體可以參考Java官方文檔。判斷字元串中是否包含某個字元串可以使用String類的matches()方法或者Pattern類的matcher()方法。
使用String類的matches()方法示例代碼:
String str1 = "hello world"; String pattern = ".*?wor.*?"; if(str1.matches(pattern)){ System.out.println("包含"); }else{ System.out.println("不包含"); }
在上面的示例中,使用正則表達式”.*?wor.*?”匹配任意個字元,包含子字元串”wor”,因此輸出結果為”包含”。
使用Pattern類和Matcher類的示例代碼:
String str1 = "hello world"; String pattern = "wor"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(str1); if(m.find()){ System.out.println("包含"); }else{ System.out.println("不包含"); }
在上面的示例中,先通過Pattern類的compile()方法編譯正則表達式,然後通過Matcher類的find()方法在字元串中尋找匹配的結果,如果有匹配的結果,則表示包含子字元串”wor”,輸出結果為”包含”。
三、使用Apache Commons Lang庫的StringUtils類
如果需要處理字元串的功能比較複雜,可以使用Apache Commons Lang庫提供的StringUtils類。StringUtils類包含了非常多的處理字元串的方法,可以方便地判斷字元串是否包含某個字元串。
使用StringUtils類的示例代碼:
String str1 = "hello world"; String str2 = "world"; if(StringUtils.contains(str1, str2)){ System.out.println("包含"); }else{ System.out.println("不包含"); }
在上面的示例中,使用StringUtils類的contains()方法判斷字元串str1是否包含字元串str2,如果包含,則輸出結果為”包含”。
四、總結
本文介紹了Java判斷字元串中是否包含某個字元串的三種方法,分別是使用String的contains()方法、使用正則表達式和使用Apache Commons Lang庫的StringUtils類。在實際開發中,應根據具體情況選擇最合適的方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/185480.html