从字符串中提取数字,添加它们并转换回字符串

时间:2014-04-04 08:05:51

标签: java regex string algorithm

我有几个类似的字符串。我想从中提取数字,添加数字并将其转换回相同的字符串格式。

逻辑应该是通用的,即它应该适用于任何给定的字符串。

示例:

  

String s1 =“1/9”;
String s2 =“12/4”;

上述两个字符串的总数应为“13/13”(再次字符串)

我知道如何从任何给定的字符串中提取数字。我提到:How to extract numbers from a string and get an array of ints?

但我不知道如何将它们重新放回相同的String格式。

任何人都可以帮助我吗?

注意:字符串格式可以是任何内容,我刚刚做了一个例子来解释。

6 个答案:

答案 0 :(得分:1)

看看这个:

public class StringTest {

    public static void main(String[] args) {
        String divider = "/";

        String s1 = "1/9";
        String s2 = "12/4";

        String[] fragments1 = s1.split(divider);
        String[] fragments2 = s2.split(divider);

        int first = Integer.parseInt(fragments1[0]);
        first += Integer.parseInt(fragments2[0]);

        int second = Integer.parseInt(fragments1[1]);
        second += Integer.parseInt(fragments2[1]);

        String output = first + divider + second;
        System.out.println(output);
    }
}

代码打印:

  

13/13

答案 1 :(得分:1)

使用正则表达式(和Markus代码)

public class StringTest {

    public static void main(String[] args) {
        String s1 = "1/9";
        String s2 = "12&4";

        String[] fragments1 = s1.split("[^\\d]");

        String[] fragments2 = s2.split("[^\\d]");

        int first = Integer.parseInt(fragments1[0]);
        first += Integer.parseInt(fragments2[0]);

        int second = Integer.parseInt(fragments1[1]);
        second += Integer.parseInt(fragments2[1]);

        String output = first + divider + second;
        System.out.println(output);
    }
}

你应该可以从这里到joining back from an array。如果你变得非常喜欢,你需要使用regular expression capture groups并将捕获的分隔符存储在某个地方。

答案 2 :(得分:1)

首先,将字符串拆分为匹配和不匹配:

  public static class Token {
    public final String text;
    public final boolean isMatch;

    public Token(String text, boolean isMatch) {
      this.text = text;
      this.isMatch = isMatch;
    }

    @Override
    public String toString() {
      return text + ":" + isMatch;
    }
  }

  public static List<Token> tokenize(String src, Pattern pattern) {
    List<Token> tokens = new ArrayList<>();
    Matcher matcher = pattern.matcher(src);
    int last = 0;
    while (matcher.find()) {
      if (matcher.start() != last) {
        tokens.add(new Token(src.substring(last, matcher.start()), false));
      }
      tokens.add(new Token(src.substring(matcher.start(), matcher.end()), true));
      last = matcher.end();
    }
    if (last < src.length()) {
      tokens.add(new Token(src.substring(last), false));
    }
    return tokens;
  }

完成此操作后,您可以创建可以迭代并处理的列表。

例如,此代码:

Pattern digits = Pattern.compile("\\d+");
System.out.println(tokenize("1/2", digits));

...输出:

[1:true, /:false, 2:true]

答案 3 :(得分:0)

该死的快速而肮脏,不依赖于知道使用了哪个分隔符。你必须确保,m1.group(2)和m2.group(2)相等(代表分隔符)。

public static void main(String[] args) {
    String s1 = "1/9";
    String s2 = "12/4";
    Matcher m1 = Pattern.compile("(\\d+)(.*)(\\d+)").matcher(s1);
    Matcher m2 = Pattern.compile("(\\d+)(.*)(\\d+)").matcher(s2);
    m1.matches(); m2.matches();
    int sum1 = parseInt(m1.group(1)) + parseInt(m2.group(1));
    int sum2 = parseInt(m2.group(3)) + parseInt(m2.group(3));
    System.out.printf("%s%s%s\n", sum1, m1.group(2), sum2);
}

答案 4 :(得分:0)

考虑功能:

public String format(int first, int second, String separator){
    return first + separator + second;
}

然后:

System.out.println(format(6, 13, "/")); // prints "6/13"

答案 5 :(得分:0)

谢谢@remus。阅读你的逻辑我能够构建以下代码。此代码解决了具有相同格式的任何给定字符串的问题。

public class Test {     public static void main(String [] args){

    ArrayList<Integer> numberList1 = new ArrayList<Integer>();
    ArrayList<Integer> numberList2 = new ArrayList<Integer>();
    ArrayList<Integer> outputList = new ArrayList<Integer>();

    String str1 = "abc 11:4 xyz 10:9";
    String str2 = "abc 9:2  xyz 100:11";

    String output = "";

    // Extracting numbers from the two similar string
    Pattern p1 = Pattern.compile("-?\\d+");

    Matcher m = p1.matcher(str1);
    while (m.find()) {
        numberList1.add(Integer.valueOf(m.group()));
    }

    m = p1.matcher(str2);
    while (m.find()) {
        numberList2.add(Integer.valueOf(m.group()));
    }

    // Numbers extracted. Printing them
    System.out.println("List1: " + numberList1);
    System.out.println("List2: " + numberList2);

    // Adding the respective indexed numbers from both the lists
    for (int i = 0; i < numberList1.size(); i++) {
        outputList.add(numberList1.get(i) + numberList2.get(i));
    }

    // Printing the summed list
    System.out.println("Output List: " + outputList);

    // Splitting string to segregate numbers from text and getting the format
    String[] template = str1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

    // building the string back using the summed list and format
    int counter = 0;
    for (String tmp : template) {
        if (Test.isInteger(tmp)) {
            output += outputList.get(counter);
            counter++;
        } else {
            output += tmp;
        }
    }

    // Printing the output
    System.out.println(output);
}

public static boolean isInteger(String s) {
    try {
        Integer.parseInt(s);
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

}

输出:

  

清单1:[11,4,10,9]   
清单2:[9,2,100,11]   
产出清单:[20,6,110,20]   
abc 20:6 xyz 110:20