【问题标题】:How to find the biggest number in a string that contains not just numbers but words?如何在不仅包含数字还包含单词的字符串中找到最大的数字?
【发布时间】:2014-03-12 19:37:36
【问题描述】:

如何在一个不仅包含数字还包含单词的字符串中找到最大的数字?

例如:

String naa = "John 19, Reuben 21, sbu 6, Derick 33";

无论输入的姓名和年龄如何,我都需要能够找到最高年龄。

【问题讨论】:

  • 哪种编程语言?

标签: string int indexof names


【解决方案1】:

我不确定您尝试使用哪种语言,但例如在 ruby​​ 中执行此操作的一种方法是

str = "John 19, Reuben 21, sbu 6, Derick 33;"
str.gsub(/\d+/).map { |i| i.to_i }.max

它的作用如下:

str.gsub(/\d+/)

将所有数字作为枚举数返回

map 命令然后将它们全部更改为整数并返回一个包含整数的数组。 然后我们就在那个数组上调用 max。

【讨论】:

    【解决方案2】:

    Java

        String[] ss = "John 19, Reuben 21, sbu 6, Derick 33;".split("[^\\d]");
        System.out.println(Arrays.asList(ss));
        int max = Integer.MIN_VALUE;
        for(String s:ss){
            try{
            if (Math.max(Integer.valueOf(s), max) != max){
                max = Integer.valueOf(s);
            }
            }catch(NumberFormatException nfe){}
        }
        System.out.println(max);
    

    【讨论】:

      【解决方案3】:

      在java中试试这个

      Pattern p = Pattern.compile("[0-9]?[0-9]");
      Matcher m = p.matcher(naa) ;  
      List<Integer> listInt = new ArrayList<Integer>();
      
      while (m.find()) {
      int age = Integer.parseInt(m.group());
          listInt.add(age);
      }
      
      int max = Collections.max(listInt);
      System.out.println( max);
      

      【讨论】:

        猜你喜欢
        • 2018-12-18
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 2018-05-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多