【问题标题】:How can I separate integer value from the following string in Java?如何在Java中将整数值与以下字符串分开?
【发布时间】:2016-08-16 16:33:49
【问题描述】:

比方说, String a="90 results";

我需要提取整数值。

【问题讨论】:

    标签: java selenium


    【解决方案1】:

    我认为Scanner 应该处理这个问题,尽管您可以向我们提供更多信息。

    例如:

    Scanner scanner = new Scanner(a);
    scanner.nextInt();
    

    【讨论】:

      【解决方案2】:

      如果整数总是用空格隔开,那么可以拆分字符串

      String res[] = a.split(" ");
      int n = Integer.parseInt(res[0]);
      

      【讨论】:

        【解决方案3】:
        import java.util.regex.Matcher;
        import java.util.regex.Pattern;
        
        public class Test {
            public static void main(String[] args) {
                String str = "90 results";
                Matcher matcher = Pattern.compile("\\d+").matcher(str);
                if (!matcher.find())
                    throw new NumberFormatException("For input string [" + str + "]");
                System.out.println(Integer.parseInt(matcher.group()));
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-10
          • 2013-05-23
          • 2018-08-24
          • 2019-10-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多