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);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40386113/article/details/107022312
今日推荐