Java中提供了多種方法來判斷一個字符串是否包含另一個字符串,可以根據場景的不同選擇不同的方法。本文將介紹Java中常見的幾種方法,以及它們的優缺點、應用場景。
一、String.contains()
String類中自帶了一個contains()方法,用於判斷該字符串是否包含指定的字符序列:
String str1 = "Hello World"; System.out.println(str1.contains("He")); //true System.out.println(str1.contains("Wo")); //true System.out.println(str1.contains("wor")); //false
該方法返回一個boolean值表示是否包含指定的字符序列。注意,contains()方法是區分大小寫的。
二、String.indexOf()
String類中的indexOf()方法也可以判斷字符串是否包含指定的字符序列,該方法會返回指定字符或字符串在原字符串中首次出現的位置,如果沒有找到則返回-1:
String str2 = "Hello World"; System.out.println(str2.indexOf("He")); //0 System.out.println(str2.indexOf("Wo")); //6 System.out.println(str2.indexOf("wor")); //-1
可以根據返回值是否等於-1來判斷該字符串是否包含指定的字符序列。同樣需要注意的事項是,indexOf()方法也是區分大小寫的。
三、String.matches()
String類中的matches()方法可以使用正則表達式來判斷該字符串是否包含指定的字符序列,返回一個boolean值表示是否匹配成功:
String str3 = "Hello World"; System.out.println(str3.matches(".*He.*")); //true System.out.println(str3.matches(".*Wo.*")); //true System.out.println(str3.matches(".*wor.*")); //false
這裡使用了”.*”來表示任意字符,matches()方法返回true表示該字符串中存在匹配正則表達式的字符序列。
四、Pattern.compile()
Pattern類和Matcher類可以組合起來實現更複雜的字符串匹配操作。Pattern.compile()可以將正則表達式編譯成Pattern對象,再利用Matcher來搜索字符串:
String str4 = "Hello World"; Pattern p = Pattern.compile("He"); Matcher m = p.matcher(str4); System.out.println(m.find()); //true System.out.println(m.start()); //0
這段代碼的結果和String.indexOf()方法類似,但是使用Pattern和Matcher可以獲得更強的靈活性,可以對正則表達式進行更多的操作。
五、StringUtils.containsIgnoreCase()
StringUtils類是Apache Commons Lang庫中提供的一個工具類,其中包含了許多常見字符串操作的工具方法,其中包括一個containsIgnoreCase()方法,用於按照不區分大小寫的方式判斷字符串是否包含指定的字符序列:
String str5 = "Hello World"; System.out.println(StringUtils.containsIgnoreCase(str5, "he")); //true System.out.println(StringUtils.containsIgnoreCase(str5, "wo")); //true System.out.println(StringUtils.containsIgnoreCase(str5, "wor")); //false
該方法返回一個boolean值,表示不區分大小寫的方式下是否包含指定字符序列。
結論:
以上介紹了Java中常用的幾種判斷字符串是否包含指定字符序列的方法,它們各有優缺點,可以根據具體的應用場景來選擇使用。String.contains()和String.indexOf()方法簡單易用,但無法使用正則表達式,適用於簡單的字符串匹配操作;String.matches()方法可以使用正則表達式,但需要更複雜的語法來進行匹配;而Pattern類和Matcher類可以組合出更靈活的匹配方案,但需要更多的代碼來實現。
在實際應用中,可以根據實際需要來選擇使用哪種方式,也可以將它們組合使用,實現更強大的字符串匹配功能。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/151407.html