一、contains方法簡介
contains是Java中String類和Collection介面中所定義的方法。它用於判斷一個字元串或集合中是否包含某個元素,返回值為true或false。使用contains方法不需要關心元素的位置,只需要關心元素是否存在。
//String中contains的用法
String str = "Hello world!";
if(str.contains("world")){
System.out.println("包含 world");
}
//Collection中contains的用法
List<String> list = new ArrayList<>();
list.add("java");
list.add("python");
if(list.contains("java")){
System.out.println("包含 java");
}
二、String中contains的用法
contains方法在String中常用於判斷一個字元串是否包含另一個字元串。String類中的contains方法的實現是利用了String類的indexOf方法。具體實現是在原字元串中查找給定子字元串的索引位置,如果索引位置不為-1則表明該子字元串存在於原字元串中,否則不存在。
另外需要注意,contains方法是區分大小寫的,也就是說如果查找的子字元串與原字元串在大小寫上不一致,contains方法會返回false。
String str = "hello world";
if(str.contains("hello")){
System.out.println("包含 hello");
}
三、Collection中contains的用法
在Collection介面實現類中,contains方法一般用於判斷集合中是否包含某個元素。Collection類中contains方法的實現是遍歷集合元素,逐一對比是否包含目標元素。
List<String> list = new ArrayList<>();
list.add("java");
list.add("python");
if(list.contains("java")){
System.out.println("包含 java");
}
四、使用contains實現模糊匹配
在實際場景中,我們有時需要在集合中進行模糊匹配,這時候可以使用contains方法。如下代碼演示了如何使用contains實現簡單的模糊匹配。
List<String> list = new ArrayList<>();
list.add("java");
list.add("python");
list.add("javascript");
String key = "java";
for(String str : list){
if(str.contains(key)){
System.out.println(str);
}
}
五、使用正則表達式實現contains方法
除了使用原生的contains方法,還可以使用正則表達式實現contains方法。正則表達式可以實現更加複雜的文本匹配,使用正則表達式實現contains方法可以更好地處理特定的匹配場景。
public static boolean contains(String src, String regex){
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(src);
return matcher.find();
}
String str = "hello world";
if(contains(str, "wor.*")){
System.out.println("包含 wor");
}
六、注意事項
在使用contains方法時,需要注意以下幾個問題:
- 在使用contains方法判斷字元串是否包含某個子字元串時,通常會先判斷該子字元串是否為空,否則會拋出空指針異常。
- 在使用contains方法判斷集合是否包含某個元素時,需要保證該元素具有正確的重寫equals方法,否則會出現判斷不準確的情況。
- 在使用正則表達式實現contains方法時,需要保證正則表達式的正確性和合理性,否則會導致匹配失敗。
原創文章,作者:GBXJ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/131875.html
微信掃一掃
支付寶掃一掃