java - 如何在java中分割复杂字符串以及如何对值求和?

标签 java string substring

我的字符串是这样的

String myString= "3:2 2:26 1:11 8:4 4:25";

在此字符串中,我想添加“:”之后(以及下一个空格之前)出现的所有数字。在本例中,结果为 2+26+11+4+25 = 68。如何使用 Reg 表达式实现此目的?

我的努力是:

if(a.contains(":")){
    for(int i=0; i<a.length(); i++) {
        if(a.contains(":")){
            int indexOFColan= a.indexOf(":");
            //System.out.println("indexOFColan:"+indexOFColan);
            //int indexWhiteSpace = a.indexOf(" ");
            String   firstValue = String.valueOf(a.charAt((indexOFColan+1)));
            System.out.println("FinalString:"+firstValue);
        } 
    }
}

最佳答案

对我有用。

    String in = "3:2 2:26 1:11 8:4 4:25";
    String[] split = in.split(" ");
    int sum = 0;

    for(int i = 0; i < split.length; i++)
    {
        try {
            sum += Integer.parseInt(split[i].split(":")[1]);
        } catch(NumberFormatException e) {
            System.out.println("Input not a number");
        }
    }

    System.out.println(sum);

关于java - 如何在java中分割复杂字符串以及如何对值求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641152/

相关文章:

java - 当 OnFocusChangeListener 应用于包装的 EditText 时,TextInputLayout 不设置动画

Java 8 Stream Reduce 任意类类型

Java "OR",有问题

java - 查找所有回文子串

c# - 如何在 C# 中搜索字符串数组中的子字符串

java构造函数行为继承和静态/动态绑定(bind)

比较相同的单词

java - 用于完成 StringBuffer 宽度的尾随空格 (Java)

JavaScript 正则表达式字符串匹配/替换

C# JSON 解析与子字符串