【问题标题】:How to extract numbers from string and count the elements between them?如何从字符串中提取数字并计算它们之间的元素?
【发布时间】:2017-07-27 16:36:14
【问题描述】:

我需要找到字符串中的所有数字并用它们做简单的算术运算。如果两个数之间的符号计数为偶数,则运算符为'+',如果计数为奇数,则运算符为'-'

输入:10plus5 - 输出:15; (10 + 5);


输入:10i5can3do2it6 - 输出:10; (10 - 5 - 3 + 2 + 6);


输入:10i5can3do2it - 输出:4; (10 - 5 - 3 + 2);

我只能为第一个示例找到解决方案:

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String input = br.readLine();
    int result = 0;
    int count = 0;
     Pattern pat = Pattern.compile("([\\d]+)([\\D]+)([0-9]+)");

     Matcher match = pat.matcher(input);

     while(match.find()){
        char[] array = match.group(2).toCharArray();
         for (int i = 0; i < array.length; i++) {
             int firstNumber = Integer.parseInt(match.group(1));
             int secondNumber = Integer.parseInt(match.group(3));
             count++;
            if(count % 2 == 0){
                result = firstNumber + secondNumber ;
            }else{
                result = firstNumber - secondNumber;
            }
        }

     }
     System.out.println(result);
}

【问题讨论】:

  • 你每次循环都会覆盖result的值,所以你只能得到最后一次计算
  • 另外,count % 2 == 0 比较需要在循环之外进行。事实上,您不需要循环。 if (array.length % 2 == 0)应该是比较
  • 谢谢我会解决这个问题,但我的问题是另一个例子。
  • 第一个示例有效的唯一原因是因为您只计算最后两个数字,而该示例仅包含两个

标签: java


【解决方案1】:

以下解决方案仅适用于input 字符串以数字开头,后跟一系列单词-数字组合(不需要以数字结尾)的情况。尚未包含对此的验证。

String input = "10i5can3do2it";     
String[] parts = input.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

int result = Integer.valueOf(parts[0]);

for (int i = 2; i < parts.length; i+=2){
    if (parts[i-1].length() % 2 == 1) {
        result -= Integer.valueOf(parts[i]);
    } else {
        result += Integer.valueOf(parts[i]);
    }
}

System.out.println(result);

打印4

正如here 所解释的那样,正则表达式在字母和数字之间进行拆分。剩下的就不用说了。

【讨论】:

    【解决方案2】:

    正如我在 cmets 中提到的,您只是在计算最后两个数字的结果。

    您需要进行计算。

    例如。 (验证所有 3 个给定输入)

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine();
    
        Pattern pat = Pattern.compile("([\\d]+|)([\\D]+)([0-9]+)");
        Matcher match = pat.matcher(input);
    
        int result = 0;
    
        while (match.find()) {
            // Pre-capture the groups
            String[] matches = new String[3];
            for (int i = 0; i < 3; i++) {
                matches[i] = match.group(i+1);
            }
    
            // Handle first number, if exists, else 0
            int firstNumber = 0;
            try {
                firstNumber = Integer.parseInt(matches[0]);
            } catch (NumberFormatException e) {}
            result+=firstNumber;
    
            // if second number doesn't exist 
            if (matches[2] == null) {
                break;
            }
    
            // when second number exists, do the logic
            int secondNumber = Integer.parseInt(matches[2]);
            if (matches[1].length() % 2 == 0) {
                result += secondNumber;
            } else {
                result -= secondNumber;
            }
        }
        System.out.println(result);
    }
    

    【讨论】:

      【解决方案3】:

      模式很简单,或许简单的做法更好,例如:

      private static int compute(String input, int index) {
          int result = 0;
          int i = index;
          while (i < input.length() && !Character.isDigit(input.charAt(i))) {
              i++;
          }
          if (i < input.length()) {
              int j = i;
              int value = 0;
              while (j < input.length() && Character.isDigit(input.charAt(j))) {
                  value = value * 10 + (input.charAt(j) - '0');
                  j++;
              }
              if (j < input.length() ){
                  result = compute(input, j);
              }
              if ((index - i) % 2  == 0){
                  result += value;
              } else {
                  result -= value;
              }
          }
          return result;
      }
      
      public static void main(String[] args) throws IOException {
          String input = "10i5can3do2it6";
          System.out.println(compute(input, 0));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-30
        • 2015-05-27
        • 1970-01-01
        • 2015-06-25
        • 2020-06-15
        • 2018-01-01
        • 2017-01-13
        • 1970-01-01
        相关资源
        最近更新 更多