gpt4 book ai didi

java - 将文本字符串读入二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:39:02 24 4
gpt4 key购买 nike

需要将一组文本字符串文件读入二维数组。文本字符串格式如下所示,每行以不同长度的“\n”结尾

    "dog", "runs", "fast"
"birds", "flies", "high"
"baby", "cries", "often", "in the evening"
"He", "works"
....

想要获得下面的二维数组输出:

  { {"dog", "runs", "fast"}, {"birds", "flies", "high"}, 
{"baby", "cries", "often", "in the evening"}, {"He", "works"},
...
}

考虑使用 StringBuilder 从文件中读取每一行并将其附加到 2D Object [][] 数组(但使用 String [][] 代替)。以下代码是我最初的尝试 - 不太漂亮,但也不起作用。

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

public class My2DArrayTest
{
public static void main(String args[])
{

String[][] myString = new String[4][3];

try
{
FileReader file = new FileReader("MyTestFile.txt");
BufferedReader reader = new BufferedReader (file);
String strLine;
String EXAMPLE_TEST;
for (int row = 0; row < 4; row++) {
for (int column = 0; column < 3; column++) {
while ((strLine = reader.readLine()) != null{

if (strLine.length() > 0) {
EXAMPLE_TEST = strLine;
System.out.println ("This is EXAMPLE_TEST: " +
EXAMPLE_TEST);


myString[row][column]=EXAMPLE_TEST;
System.out.println("Current row: " + row);
System.out.println("Current column: " + column);
System.out.println("This is myString Array:" +
myString[row][column] + " ");
}
}
}
}
file.close();

} catch( IOException ioException ) {}
}
}

最佳答案

首先,您必须决定如何处理您不知道开始时的行数这一事实。你可以:

  1. 首先计算行数以创建所需大小的结果数组,然后再次读取文件并用数据填充该数组。
  2. 将您的行存储在 List 中。

(我会选择2)其次,您希望在字符串中允许使用哪些字符?例如 "\n (换行符)会让事情变得更复杂,因为你必须转义它们,但我们假设这些字符将被禁止(还有 ​​,,这样我们就可以更容易地拆分)

Scanner in = new Scanner(new File("strings.test"));
List<String[]> lines = new ArrayList<>();
while(in.hasNextLine()) {
String line = in.nextLine().trim();
String[] splitted = line.split(", ");
for(int i = 0; i<splitted.length; i++) {
//get rid of additional " at start and end
splitted[i] = splitted[i].substring(1, splitted[i].length()-1);
}
lines.add(splitted);
}

//pretty much done, now convert List<String[]> to String[][]
String[][] result = new String[lines.size()][];
for(int i = 0; i<result.length; i++) {
result[i] = lines.get(i);
}

System.out.println(Arrays.deepToString(result));

输出:

[[dog, runs, fast], [birds, flies, high], [baby, cries, often, in the evening], [He, works]]

如果您需要我“丢弃”的任何特征,请在评论中告诉我,我将编辑此答案。

关于java - 将文本字符串读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24924937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com