删除 ArrayList 中的所有空格。 Java

Removing all spaces in an ArrayList. Java

我正在从 .txt 文件中获取输入并将其存储到 ArrayList 中。我需要去掉所有 space,这样我才能将 ArrayList 解析为 <Integer>。我将 post 注释掉部分,这样您就可以看到我尝试使用的方法来执行此操作。谢谢你。如果能给我个地方看看就好了

import java.io.*;
import java.util.*;

public class LabWriterReadre {

  public static void main(String [] args){
       BufferedReader br = null;
       BufferedWriter bw = null;
      // fileWriter = new FileWriter("output.txt",false);
       ArrayList<String> storage = new ArrayList<String>();
       ArrayList<String> convertToInt = new ArrayList<String>();
       ArrayList<Integer> matrix = new ArrayList<Integer>();
         String strLine = "";
        int row1,col1,row2,col2; 

        try {
            br = new BufferedReader( new FileReader("C:/Users/jeremiahlukus/Desktop/New folder/jj.txt"));
            while( (strLine = br.readLine()) != null)
            {
                System.out.println(strLine);
                storage.add(strLine);             
            }
        } catch (FileNotFoundException e) {
            System.err.println("Unable to find the file: fileName");
        } catch (IOException e) {
            System.err.println("Unable to read the file: fileName");
        }


        /*
        String[] trimmedArray = new String[string.size()];
        for (int i = 0; i < string.size(); i++)
        {
            trimmedArray[i] = string[i].trim();
            string.removeAll(Arrays.asList(null,""));
        }
        */
        //string.removeAll(Collections.singleton(""));
       // string.removeAll(Arrays.asList(null,"")

      for (String str : storage)
      {
         if (//str != " ")
             !str.isEmpty())
         {
          convertToInt.add(str);
          //convertToInt.trim();

         }
     }

System.out.println(convertToInt);
}

 /* 

       row1 = Integer.parseInt(convertToInt.get(0));
       col1 = Integer.parseInt(convertToInt.get(1));
       row2 = Integer.parseInt(convertToInt.get(2));
       col2 = Integer.parseInt(convertToInt.get(3));

       int[][] matrix1=new int[row1][col1];
       int[][] matrix2=new int[row2][col2];

     */  

      //  System.out.println(row1);


        /*

这是我正在阅读的.txt文件,_表示space

3___________3
3_4

1 ______2 3 
4_5 _6
7 _8 _9

1 _2_ 3_ 4
5 _6 _7 _8
9_ 10_ 11_ 12

这是打印出来的 ArrayList

[3______3,_3 _4,__ 1_______2_ 3 , ___4 _5 _6, 7_ 8 _9, 1_ 2_ 3_ 4, 5 _6_ 7_ 8, 9 _10_ 11_ 12]

这就是我想要发生的事情

[3,3,3,4,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,10,11,12]

您可以在添加该行时只执行 replace(" ", "") 。此外,还可以使此代码更加高效。

在读取数组中的文件时,尝试使用 replaceAll() 删除所有空格。

while( (strLine = br.readLine()) != null)
{
     System.out.println(strLine);
     storage.add(strLine.replaceAll("\s+",""));             
}

我可能错了,但看起来你的代码可以通过类似

的方式解决和简化一点
Scanner input = new Scanner(new File("C:/Users/jeremiahlukus/Desktop/New folder/jj.txt"));
List<Integer> numbers = new ArrayList<>();
while(input.hasNextInt()){
    numbers.add(input.nextInt());
}

我在这里假设您的文件仅包含由空格分隔的数字(其中还包括行分隔符)。

每一行都可以用这样的正则表达式进行解析

List<String> sequence = new ArrayList<String>();
Patter noSpacesPattern = Pattern.compile("(\S+)");
Matcher matches;

// reading your line from file here, now for each line do this

matches = noSpacesPattern.matcher(strLine);

while (matches.find())
    sequence.add(matches.group());

这将清除不必要的空间并使您的代码更易读。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {

  public static void main(String[] args)
  {

      String total="";
      List list=new ArrayList();
    list.add("3______3");
    list.add("_3 _4");
    list.add("__ 1_______2_ 3");
    list.add("3 ");
    list.add(" ___4 _5 _6");
    list.add(" 7_ 8 _9");

    list.add(" 1_ 2_ 3_ 4");
   list.add(" 5 _6_ 7_ 8");
   list.add(" 9 _10_ 11_ 12");

      String firstname1 = list.toString();
      String regex = "[0-9]+";
      firstname1 = firstname1.replaceAll("_", ",");

      firstname1 = firstname1.replace(",", ",");

      String str = firstname1.toString().replaceAll("\s+", ",").replace("[", "").replace("]", "");

      String arr[] = str.split(",");

      for (int i = 0; i < arr.length; i++) {
          if (arr[i].matches(regex)) {

              total += arr[i] + ",";
          }
      }
      total = total.substring(0, total.length() - 1);
      List finalList = Arrays.asList(total);

      System.out.println(finalList);
     //output-->> [3,3,3,4,1,2,3,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,10,11,12]
  }
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {

  public static void main(String[] args) throws FileNotFoundException, IOException
  {
      String total="";
      List list=new ArrayList();


         try {
           BufferedReader br = new BufferedReader( new FileReader("filename.txt"));
            while( (total = br.readLine()) != null)
            {
           list.add(total);             
            }
            br.close();

        } catch (FileNotFoundException e) {
            System.err.println("Unable to find the file: fileName");
        }

      String firstname1 = list.toString();
      String regex = "[0-9]+";
      firstname1 = firstname1.replaceAll("_", ",");

      firstname1 = firstname1.replace(",", ",");

      String str = firstname1.toString().replaceAll("\s+", ",").replace("[", "").replace("]", "");

      String arr[] = str.split(",");
      String sum="";
      for (int i = 0; i < arr.length; i++) {

          if (arr[i].matches(regex)) {

              sum += arr[i] + ",";

          }
      }
      sum = sum.substring(0, sum.length() - 1);
      List finalList = Arrays.asList(sum);

      System.out.println("finallist-->>>"+finalList);
     //output-->> [3,3,3,4,1,2,3,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,10,11,12]
  }
}