get only integer values of a string and find second maximum

时间:2017-11-02 15:40:17

标签: java string int

Given the String: "1 22a 34 718 u3ou1." The aim is to find only the int values, in this case it's 1 and 34 and 718. I tried it like this:

    String str = "1 22a 34 718 u3ou1.";      
    str = str.replaceAll("[^-?0-9]+", "*"); 
    System.out.println(Arrays.asList(str.trim()));

The output of this is: [1 22 34 718 3 1]. The output should be: [1 34 718]. Can someone find the bug?

2 个答案:

答案 0 :(得分:0)

更好地利用分裂,我相信:

private List<int> intArray(string str)
{
 data = str.Split('');
 var result = new List<int>();
 for (var item in data)
 {
   int number=0;
   if (int.TryParse(item,out number))
   {
         result.Add(number);
   }
 }

 return result
}

警告: 1.没有检查/测试代码

2 ..我刚刚意识到问题出在java中,而我的代码是C#

答案 1 :(得分:0)

你可以尝试解析元素,在使用空格作为分隔符分割之后:

String str = "1 22a 34 718 u3ou1.";

String[] split = str.split(" +");

    List<String> list = new ArrayList<>();

    for (String s : split) {
        try {
            Integer.parseInt(s);
            list.add(s);
        } catch (NumberFormatException e) {

            /**
             *
             *do Nothing
             *
             * */
        }
    }
    System.out.println(list);