一、使用contains方法
判斷一個字元串是否包含另一個字元串,可以使用Java內置的contains方法。
String str1 = "Hello, World!"; String str2 = "Hello"; boolean result = str1.contains(str2); if(result) { System.out.println("str1包含str2"); } else { System.out.println("str1不包含str2"); }
二、使用indexOf方法
另一種常見的方法是使用indexOf方法,通過返回值是否大於等於0來判斷是否包含。
String str1 = "Hello, World!"; String str2 = "Hello"; int result = str1.indexOf(str2); if(result >= 0) { System.out.println("str1包含str2"); } else { System.out.println("str1不包含str2"); }
三、使用正則表達式
如果需要進行更複雜的判斷,可以使用正則表達式。如下面的示例,判斷字元串是否包含數字。
String str = "Hello 123 World!"; boolean result = str.matches(".*\\d.*"); if(result) { System.out.println("str包含數字"); } else { System.out.println("str不包含數字"); }
四、使用split方法
使用split方法可以將字元串按照指定的字元或正則表達式拆分成字元串數組,如果拆分後的數組長度大於1,那麼原字元串就包含了拆分的字元。
String str1 = "Hello, World!"; String str2 = ","; String[] arr = str1.split(str2); if(arr.length > 1) { System.out.println("str1包含str2"); } else { System.out.println("str1不包含str2"); }
五、使用CharSequence介面
CharSequence介面是Java中用於表示字元序列的介面,可以方便地進行判斷操作。
String str1 = "Hello, World!"; CharSequence cs = "Hello"; boolean result = str1.contains(cs); if(result) { System.out.println("str1包含cs"); } else { System.out.println("str1不包含cs"); }
六、小結
在Java中,判斷一個字元串是否包含指定字元有多種方法,可以根據實際情況選擇合適的方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/237665.html