阵列拆分零件时的字符串错误

时间:2016-09-17 06:15:50

标签: java

 String part1=parts[0];
 String part2=parts[1];
 String part3=parts[2];
 System.out.print(part3);      
sdddd asd asd asd asd asd asdasdasd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asd asdasdasdasd asd as asd asdas dasd as dasd asdasdasdasdasdasd

3 个答案:

答案 0 :(得分:2)

您可以检查数组的长度:

template <typename T>
constexpr typename std::add_const<T>::type& as_const(T& t) noexcept{
    return t;
}

答案 1 :(得分:0)

if (string.contains("-")) {
         parts= string.split("d|\\-");    
         String part1=parts[0];
         String part2=parts[1];
         String part3=parts[2];
        }else{
             parts= string.split("d");    
             String part1=parts[0];
             String part2=parts[1];
        }

          for (int i = 0; i < parts.length; i++) {
                System.out.println(parts[i]);
                }

答案 2 :(得分:0)

带有捕获组的正则表达式可用于解析String。只需检查组的String是否为null,您就可以测试各个组的存在。例如:

Pattern pattern = Pattern.compile("(\\d+)d(\\d+)([+-]\\d+)?");

for (String s : new String[] {
    "2d6",
    "3d8",
    "4d6-2",
    "4d6+9",
    "2d6-10",
    "2d6-1x9"
}) {
    System.out.println(s);
    Matcher m = pattern.matcher(s);
    if (m.matches()) {
        int i1 = Integer.parseInt(m.group(1));
        int i2 = Integer.parseInt(m.group(2));
        String summand = m.group(3);
        int i3 = summand == null ? 0 : Integer.parseInt(summand);
        System.out.println(MessageFormat.format("{0}D{1}+({2})", i1, i2, i3));
    } else {
        System.out.println("no match");
    }
}

输出:

2d6
2D6+(0)
3d8
3D8+(0)
4d6-2
4D6+(-2)
4d6+9
4D6+(9)
2d6-10
2D6+(-10)
2d6-1x9
no match