计算混合字符串中的数字总和

时间:2015-05-13 04:28:02

标签: string

如何获得以下字符串

中的数字总和
1..4..2..6..2.212.4.11|1..4..2..6..2.|.212.4.111..2.3.444

我试过这个

String plrinfo[]=sLine.split("\\|");


            for (String plrinfo1:plrinfo) {

                System.out.println(plrinfo1);

            String[] numbers=plrinfo1.split("\\.");
            int sum=0;
                for(int i=0;i<numbers.length;i++){
                    System.out.println(numbers[i]);


            sum=sum+Integer.parseInt(numbers[i]);
            return sum

但它不起作用

2 个答案:

答案 0 :(得分:0)

import java.util.Scanner;

public class Test {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner s = new Scanner(System.in);
    int sum = 0;
    String ip = s.nextLine();
    //replace . with space
    String ip1 = ip.replace(".", " ");
    //replace | by space
    String ip2 = ip1.replace("|", " ");
    //split string by spaces
    String[] fin = ip2.split("\\s+");
    for (int i = 0; i < fin.length; i++) {
        sum = sum + Integer.parseInt(fin[i]);
    }
    System.out.println(sum);
}

}

答案 1 :(得分:0)

您可以使用正则表达式(正则表达式)作为字符串分隔符。此分隔符包含一个或多个“。”或“|”。

更新:添加函数 sumIndividualDigits(String str)以获取数字的每个数字的摘要。

示例代码:

public class CalculateNumber {

private static final String TEXT = "1..4..2..6..2.212.4.11|1..4..2..6..2.|.212.4.111..2.3.444";

private static final String REGEX = "(\\.|\\|)+";

public static void main(String[] args) {
    String[] numbers = TEXT.split(REGEX);
    int sum = 0;
    for(String e : numbers) {
//            sum += Integer.valueOf(e);
//            System.out.print(e + ",");    
        int part = sumIndividualDigits(e);
        System.out.print(part + ",");
        sum += part;

    }
    System.out.println("\nSum: " + sum);
}

public static int sumIndividualDigits(String str) {

    char[] digits = str.toCharArray();
    int sum = 0;

    for(char c : digits) {
        int digit = Integer.valueOf(String.valueOf(c));
        sum += digit;
    }
    return sum;
}

}

输出是:

1,4,2,6,2,5,4,2,1,4,2,6,2,5,4,3,2,3,12,
Sum: 70