gpt4 book ai didi

java - 删除 ArrayList 中的所有空格。 java

转载 作者:行者123 更新时间:2023-12-02 03:58:57 25 4
gpt4 key购买 nike

我正在从 .txt 文件获取输入并将其存储到 ArrayList 中。我需要删除所有空格,以便我可以解析 ArrayList<Integer> 。我将发布注释掉的部分,以便您可以看到我尝试使用什么来执行此操作。谢谢。如果你能给我一个地方看看那就太好了。

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 文件,_表示空间

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]

最佳答案

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

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());

这将清除不必要的空间,并使您的代码具有良好的可读性。

关于java - 删除 ArrayList 中的所有空格。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35105344/

25 4 0