引言
在Java程序中,我們需要使用字元串操作的情況很多,其中一種常見的需求就是判斷一個字元串中是否包含某個子串。Java提供了String類的contains方法來滿足這一需求。本文將詳細介紹contains方法的使用和實例。
正文
1. contains方法介紹
String類的contains方法用於判斷一個字元串是否包含某個子串,返回值為true或false。contains方法的聲明如下:
public boolean contains(CharSequence s)
其中,參數s為要查找的子串,返回值為boolean類型。
2. contains方法使用示例
下面是contains方法的使用示例代碼:
public class ContainsDemo {
public static void main(String[] args) {
String str = "Hello, world!";
// 判斷字元串中是否包含指定子串
boolean result1 = str.contains("world");
boolean result2 = str.contains("Java");
// 輸出結果
System.out.println("字元串中是否包含'world':" + result1);
System.out.println("字元串中是否包含'Java':" + result2);
}
}
該程序輸出的結果如下:
字元串中是否包含'world':true
字元串中是否包含'Java':false
3. contains方法使用案例
判斷手機號碼格式是否正確
在開發過程中,我們經常需要驗證用戶輸入的手機號碼格式是否正確。因為手機號碼格式比較複雜,所以需要使用正則表達式來檢查格式。不過,我們可以先使用contains方法來判斷字元串中是否包含非法字元從而快速判斷手機號碼格式是否正確。
下面是一個判斷手機號碼格式是否正確的示例代碼:
public class PhoneNumberValidator {
public static void main(String[] args) {
String phoneNumber = "13612345678"; // 假設這是用戶輸入的手機號碼
// 判斷手機號碼中是否包含非法字元
boolean isValid = true;
if (!phoneNumber.contains("+") && !phoneNumber.contains("-")) {
// 手機號碼不包含+或-等非法字元,進行正則表達式驗證
String regex = "^1[3-9]\\d{9}$";
isValid = phoneNumber.matches(regex);
} else {
isValid = false;
}
// 輸出結果
if (isValid) {
System.out.println("手機號碼格式正確!");
} else {
System.out.println("手機號碼格式錯誤!");
}
}
}
當用戶輸入的手機號碼符號要求時,程序輸出:
手機號碼格式正確!
當用戶輸入的手機號碼不符合要求時,程序輸出:
手機號碼格式錯誤!
在字元串數組中查找特定的字元串
假如我們有一個字元串數組,其中包含若干個字元串。現在我們需要在數組中查找某個特定的字元串,可以使用contains方法來實現。
下面是一個在字元串數組中查找特定的字元串的示例代碼:
import java.util.Arrays;
public class StringArray {
public static void main(String[] args) {
String[] strArray = {"hello", "world", "Java", "is", "great"};
// 在字元串數組中查找特定的字元串
boolean result1 = Arrays.stream(strArray).anyMatch(str -> str.contains("world"));
boolean result2 = Arrays.stream(strArray).anyMatch(str -> str.contains("Python"));
// 輸出結果
System.out.println("數組中是否包含'world':" + result1);
System.out.println("數組中是否包含'Python':" + result2);
}
}
該程序輸出的結果如下:
數組中是否包含'world':true
數組中是否包含'Python':false
結論
contains方法是Java String類中非常實用的方法,用於判斷一個字元串中是否包含某個子串,它簡單易用,可以幫助我們快速解決許多字元串操作問題。
原創文章,作者:KMWM,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/135879.html
微信掃一掃
支付寶掃一掃