java獲取字符串中括號中的內容

例如,有字符串"採集ID:[1400020338]的層信息已存在!請修改後再次上報!"

需要根據字符串中的id對具體的數據表數據進行操作,因此首先需要截取到裏面的id。

具體操作方式如下

String strInfo = "採集ID:[1400020338]的層信息已存在!請修改後再次上報!";

private int getId(String strInfo){

        String idInfo = strInfo.substring(strInfo.indexOf("[")+1,strInfo.indexOf("]"));

        if(StringUtil.isEmpty(idInfo)){

                 return 0;

        }

        return Integer.parseInt(idInfo);

}

判斷一個字符串中是否包含某個字符串的方法:

方法一:startsWith();

這個方法有兩種方式,

public boolean startsWith(String prefix, int toffset)
public boolean startsWith(String prefix)

prefix:是指要匹配的前綴;

toffset:從哪裏開始尋找字符串。

返回值爲true或者false

方法二:contains方法

該方法返回值爲true或false。該方法只對用於char類型值

String str = "abc";

boolean status = str.contains("a");

方法三:indexOf()方法

indexOf()的用途是在一個字符串中尋找指定字符的位置,同時也可以判斷一個字符串中是否包含某個字符

indexOf()的返回值是int

public static void main(String[] args) {
    String str1 = "abcdefg";
    int result1 = str1.indexOf("ab");
    if(result1 != -1){
        System.out.println("字符串str中包含子串“ab”"+result1);
    }else{
        System.out.println("字符串str中不包含子串“ab”"+result1);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章