【问题标题】:Extracting Ints from Strings in Java从 Java 中的字符串中提取整数
【发布时间】:2016-06-05 19:21:07
【问题描述】:

我正在尝试编写一个采用 String 的方法,在其中查找 Ints 然后将它们相加。

例如:

    String s = "five5six66"

应该返回 5+66 = 71 或者:

    String s = "1ciao2three3"

应该返回 1+2+3 = 6

以下是我已经写的,但是当我运行它时,我得到了一个

    NumberFormatException

代码(更新 1):

    public static int addNumbers(String s) {
    String numbers="";
    int addNumbers = 0;
    int i;
    char c;

    for (i=0; i<s.length(); i++) {
        if (s.charAt(i)>='0' && s.charAt(i)<='9') {
            c = s.charAt(i);
            while (i<s.length()-1) {
                if (s.charAt(i+1)>='0' && s.charAt(i+1)<='9')
                    numbers = numbers.valueOf(c + s.charAt(i+1));
                addNumbers = addNumbers + Integer.parseInt(numbers);
            }
            addNumbers = addNumbers + Character.getNumericValue(c);
        }
    }
    return addNumbers;
}

希望你能帮我修复这段代码,请让我明白我做错了什么!

如果我有这样的字符串,我也可以扩展它:

    String s = "hi123and27"

我可以得到 123+27 = 150?

因为我现在的代码仅限于 2 位数字。

【问题讨论】:

  • 考虑对该方法使用正则表达式
  • This:s.charAt(i+1) 在 for 循环中是一件非常危险的事情。想一想为什么,问题就会变得显而易见。
  • @HovercraftFullOfEels 谢谢我明白了!这就是为什么我得到 IndexOutOfBound 但是我怎样才能在一个字符串中连接 2 个连续的数字呢?
  • 您可以将 char 存储在一个变量中,如果下一个 char 仍然是数字,则将它们连接起来——即向后看但不要向前看。您遇到了“边界条件”,需要仔细考虑。
  • 好的!我会尝试更新我的代码!

标签: java string int


【解决方案1】:

我建议使用 REGEX 来满足您的要求:

你需要:

  1. 正则表达式模式:"\d+"
  2. 一个累加器,用于连接您从给定字符串中获得的值

示例:

public static void main(String[] args) {
    String s = "hi123and27";
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(s);
    int accumulator  = 0;
    while (m.find()) {
        accumulator  += Integer.parseInt(m.group());
    }
    System.out.println("final result: " + accumulator );
}

【讨论】:

  • 我是 Java 和一般开发的初学者,我想使用更“基本”的东西,谢谢你的回答!
【解决方案2】:

正则表达式 + Java 8 流:

public static int addNumbers(String str) {
    return Arrays.stream(str.replaceAll("[^0-9]", " ").split(" "))
            .filter(s -> !s.isEmpty())
            .mapToInt(Integer::parseInt)
            .sum();
}

关于建议的编辑是 cmets:

public static int addNumbers(String str) {
    return Arrays.stream(str.split("[^0-9]+"))
            .filter(s -> !s.isEmpty())
            .mapToInt(Integer::parseInt)
            .sum();
}

【讨论】:

  • 用另一个非数字字符替换每个非数字字符以拆分另一个字符有什么意义?只需拆分非数字字符并跳过多余的replaceAll 调用。并使用[^0-9]+ 而不是[^0-9] 来减少空条目的数量(减少s.isEmpty() 检查)。
  • @Tom 你的观点是正确的,这里真的不需要 {replaceAll},我会更新关于你推荐的答案
【解决方案3】:

试试这个

public static void main(String [] args){

    String string = "hi123and27";

    int size = string.length();

    int sum = 0;
    StringBuilder val = new StringBuilder();

    for (int idx = 0; idx < size; idx++) {
        Character character = string.charAt(idx);

        if (Character.isDigit(character)) {
            val.append(character);

            //if last character is a digit
            if((idx+1 == size) && val.length() > 0)
                sum += Integer.parseInt(val.toString());

        }else{
            if(val.length() > 0)
                sum += Integer.parseInt(val.toString());

            //reset the val for digits between characters for it to store the next sequence
            val.setLength(0);
        }
    }

    System.out.println("The sum is : " + sum);
}

【讨论】:

  • 这个方法好像不行。这是我得到的结果:jhdsg1kjhgd2 - [3] = 2 和 75sg1kjhgd23 - [99] = 23
  • 请再检查一遍,刚刚执行了String s = "hi123and27" 得到了150,其实我已经执行了你给出的所有例子75sg1kjhgd23=99, and Five5six66=71, 1ciao2three3=6
  • 感谢它的工作!另一个问题,In 'sum += Integer.parseInt(val.toString());' '+=' 是什么意思?
  • 只是快捷方式: sum = sum + Integer.parseInt(val.toString());请为答案投票。
【解决方案4】:

你应该试试这个。

public static int addNum(String text){
    String numbers = "";
    int finalResult = 0;

    for(int i=0;i < text.length();i++){

        if(isNumeric(text.substring(i, i + 1)))
        {
            numbers += text.substring(i, i + 1);

            if(i==text.length()-1) {
                finalResult += Integer.parseInt(numbers); 
            }
        }else {
            if(!numbers.equals("")){
                finalResult += Integer.parseInt(numbers);
                numbers = "";
            }
        }
    }
    return finalResult;
}

public static boolean isNumeric(String str)  
{  
  try{  
    int d = Integer.parseInt(str);  
  }  
  catch(NumberFormatException ex){  
    return false;  
  }
  return true;  
}

【讨论】:

  • 我喜欢你的回答,我正在测试它。你能解释一下 try and catch 是如何工作的吗?
  • 试过这个。对于 s = "75sg1kjhgd23" 我得到 7+5+1+2+3 = 18。我需要 75+1+23 = 99
  • Try catch 块用于捕获异常,因此当 try 块语句中发生异常时,执行控制权将传递给 catch 块。这是不可能的,因为我已经尝试过了,结果是 99。
  • 好吧,我不知道为什么它以前不起作用。可能我打错了什么。 += 是什么意思?在 finalResult += Integer.parseInt(numbers);
  • 快捷方式:finalResult = finalResult + Integer.parseInt(numbers);
猜你喜欢
  • 2020-07-20
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
相关资源
最近更新 更多