50,530
社区成员
发帖
与我相关
我的任务
分享
String strTmp = m.group();
// 按位拆分,判断字符0的个数
int sum = 0;
for (int i = 0; i < strTmp.length(); i++) {
if ('0' == strTmp.charAt(i)) {
sum++;
}
}
// 如果有4个0,则说明串符合要求
if (sum == 4) {
System.out.println(s + "字符串中,由4个0,2个1组成的字串为:" + strTmp);
} else {
System.out.println("字符串" + strTmp + "中,0与1的个数不符合要求");
}
// 目标串,稍微扩展了下
String s = "00012000110020100000";
// 只包含0、1的匹配
Pattern p01 = Pattern.compile("[01]{6}");
Matcher m = p01.matcher(s);
// 先找到长度为6的0、1串
while (m.find()) {
String strTmp = m.group();
// 按位拆分,将6位数相加,和为2,则表示有4个0,2个1
int sum = 0;
for (int i = 0; i < strTmp.length(); i++) {
sum += Integer.valueOf(strTmp.substring(i, i + 1));
}
if (sum == 2) {
System.out.println(s + "字符串中,由4个0,2个1组成的字串为:" + strTmp);
} else {
System.out.println("字符串" + strTmp + "中,0与1的个数不符合要求");
}
}