情景展示
判斷String類型里是否包含指定字符
String lineText = "cz8108_1接口業務參數:{\"EInvoiceNumber\":\"0003656276\",\"EInvoiceCode\":\"41060221\",\"AgencyCode\":\"0000510000025760\",\"RandomNumber\":\"126501\"}";
方式一:indexOf()
大小寫敏感(區分大小寫);
存在,返回第一次出現的下標索引數;不存在,返回-1;
通常與截取字符串結合使用。
System.out.println(lineText.indexOf("cz8108_1接口業務參數:"));// 0 System.out.println(lineText.indexOf("cz8108接口業務參數:"));// -1
如果想用它來判斷是否指定字符串的話,可以和-1進行對比:
-1,表示不包含,>=0代表包含。
System.out.println(lineText.indexOf("cz8108_1接口業務參數:") > -1);// true System.out.println(lineText.indexOf("cz8108接口業務參數:") >= 0);// false
方式二:contains() 推薦使用
大小寫敏感(區分大小寫);
存在,返回true;不存在,返回false;
System.out.println(lineText.contains("cz8108_1接口業務參數:"));// true System.out.println(lineText.contains("cz8108接口業務參數:"));// false
點擊contains()方法,我們可以查看源碼,會發現:
它的使用方法和方式一,一模一樣
方式三:正則表達式
同上
Pattern p = Pattern.compile("cz8108_1接口業務參數:"); System.out.println(p.matcher(lineText).find());// true p = Pattern.compile("cz8108接口業務參數:"); System.out.println(p.matcher(lineText).find());// false
方式四:第三方工具類
由apache的commons-lang3.jar包提供
System.out.println(StringUtils.contains(lineText, "cz8108_1接口業務參數:"));// true System.out.println(StringUtils.contains(lineText, "cz8108接口業務參數:"));// false
有個使用的功能是,它提供了不區分大小的方法:
System.out.println(StringUtils.containsIgnoreCase(lineText, "einvoicenumber"));// true System.out.println(StringUtils.containsIgnoreCase(lineText, "EINVOICENUMBER"));// true
containsIgnoreCase()比較實用。