如何只提取数字并从文本文件中升序排序包含String和Int?

时间:2017-11-23 19:24:40

标签: java arrays regex loops

我是Java的初学者。 请指点我解决问题的方向。 下面的代码是我尝试过的,只提取了数字。 那之后我迷路了。

public class regex {

    public static String str = "9, a, R, 3, 60, Z, 40, 30, 33, 29, DDD, aaa, !!, 21, 88, s, q, l, z, 2, a";

    public static void main (String[] args) throws FileNotFoundException {

        str = str.replaceAll("[^-?0-9]+", " ");

        System.out.println(Arrays.asList(str.trim().split(" ")));
    }
}

控制台:

num:29
num:30
num:33
num:40
num:60
num:88

3 个答案:

答案 0 :(得分:1)

首先,正则表达式需要一些修复:

str = str.replaceAll("[^-?0-9]+", " ");

问题在于它不会取代输入中的 ?。 可能这不是你想要的。 你可能希望在-后跟一个数字, 否则删除。 你可以通过两次替换来做到这一点:

str = str
    .replaceAll("[^-0-9]+", " ")
    .replaceAll("-(?![0-9])", " ");

现在,您可以安全地在一个或多个空格上拆分字符串。 然后从String创建String[]的流, 然后将其映射到int值, 排序, 最后创建一个数组:

int[] ints = Arrays.stream(str.split(" +"))
    .mapToInt(Integer::parseInt)
    .sorted()
    .toArray();

System.out.println(Arrays.toString(ints));

我觉得另一种方法更容易理解, 是代替分裂, 使用Pattern

提取数字序列
Pattern pattern = Pattern.compile("(-?\\d+)");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    nums.add(Integer.parseInt(matcher.group()));
}

Collections.sort(nums);
System.out.println(nums);

答案 1 :(得分:1)

你可以用这种方法做到:

1.仅提取字符串到数组列表中的数字。

2.使用集合排序数组列表中的数字。

public static boolean isNumeric(String str)  
{  
    try  
    {  
      int num = Integer.parseInt(str);  
    }  
    catch(Exception e)  
    {  
      return false;  
    }  
    return true;  
}
public static void main(String[] args) {

     String str = "9, a, R, 3, 60, Z, 40, 30, 33, 29, DDD, aaa, !!, 21, 88, s, q, l, z, 2, a";
     ArrayList<Integer> numList = new ArrayList<Integer>();
     String[] strArr = str.split(",");
     for(int i = 0; i < strArr.length; i++){
           if(isNumeric(strArr[i].trim())){
               numList.add(Integer.parseInt(strArr[i].trim()));
           }
     }
     Collections.sort(numList);
     System.out.println(numList);
}

<强>输出

[2, 3, 9, 21, 29, 30, 33, 40, 60, 88]
BUILD SUCCESSFUL (total time: 0 seconds)

答案 2 :(得分:-1)

希望以下代码能够回答您的问题:它只是从输入文件中读取每一行,并使用split方法提取字符串并将其存储在数组中。然后它尝试将字符串转换为int。如果字符串是一个数值,它将转换为int并将其添加到arraylist。如果不是,它将跳过。然后它使用Collections.sort方法对arraylist进行排序并显示结果。

package TrialPrograms;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;

public class Stacktraceq2 {

    private static final Exception Exception = null;

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        FileInputStream fi = new FileInputStream("F:\\SeleniumTCs\\input.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fi));

        String strLine;
        ArrayList<Integer> nos = new ArrayList<Integer>();
        while ((strLine = br.readLine()) != null)   {
              // Print the content on the console
              String[] arr = strLine.split(" ");

              for(int i=0;i<=arr.length-1;i++) {
                  try {
                  int no=Integer.parseInt(arr[i]);
                  nos.add(no);
                  }
                  catch(NumberFormatException e) {

                  }
              }
              Collections.sort(nos);

                }
        System.out.println("The Numbers in Ascending Order");
        for(int i:nos) {
            System.out.println(i);

    }

}

    }