【问题标题】:JAVA : String Manipulation using Split functionJAVA:使用拆分功能的字符串操作
【发布时间】:2018-10-16 09:13:57
【问题描述】:

我有一个字符串“AB12TRHW4TR6HH58”,我需要拆分这个字符串,每当我找到一个数字时,我都需要执行所有的加法。但是,如果有连续的数字,那么我需要将它作为一个整数。 例如,在上面的字符串中,加法应该像 12+4+6+58 等等。

我在下面编写了单独添加所有数字但不能取整数的代码。你能帮忙吗?

public class TestClass {

    public static void main(String[] args) {



        String str = "AB12TRHW4TR6HH58";

        int len = str.length();
        String[] st1 = str.split("");
        int temp1=0;
        for(int i=0;i<=len-1;i++){


                        if(st1[i].matches("[0-9]")){


                        int temp = Integer.parseInt(st1[i]);

                        temp1 = temp+temp1;
                    }

                }

        System.out.println(temp1);

    }

}

【问题讨论】:

标签: java string


【解决方案1】:

按照我在评论中所说的去做:

    String str = "AB12TRHW4TR6HH58";

    String[] r = str.split("[a-zA-Z]");
    int sum = 0;
    for ( String s : r ) {
        if ( s.length() > 0 ) {
            sum += Integer.parseInt(s);
        }
    }

    System.out.println(sum);

【讨论】:

  • 非常感谢斯蒂芬。这很完美,很容易理解
【解决方案2】:

您可以拆分非数字字符并使用结果数组:

String[] st1 = "AB12TRHW4TR6HH58".split("[^0-9]+");
int temp1 = 0;
for (int i = 0; i < st1.length; i++) {
    if (st1[i].isEmpty()) {
        continue;
    }

    temp1 += Integer.parseInt(st1[i]);
}

System.out.println(temp1);

甚至可以使用流进一步简化:

int temp1 = Stream.of(st1)
                .filter(s -> !s.isEmpty())
                .mapToInt(Integer::new)
                .sum();

【讨论】:

  • 效果很好。非常感谢
【解决方案3】:

不要拆分您想要省略的部分,只需搜索您需要的内容:数字。使用 MatcherStream 我们可以这样做:

String str = "AB12TRHW4TR6HH58";
Pattern number = Pattern.compile("\\d+");
int sum = number.matcher(str)
        .results()
        .mapToInt(r -> Integer.parseInt(r.group()))
        .sum();
System.out.println(sum); // 80

或使用附加映射但仅使用方法引用:

int sum = number.matcher(str)
        .results()
        .map(MatchResult::group)
        .mapToInt(Integer::parseInt)
        .sum();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2016-01-21
    • 2022-11-11
    相关资源
    最近更新 更多