简体   繁体   English

从文本文件中读取空格到Char / String数组中

[英]Reading white spaces from a text file into Char/String array

I am trying to read and create a multi-dimensional array of char (not possible?) or String from a text file splitting each char/symbol/space. 我正在尝试从拆分每个char / symbol / space的文本文件中读取和创建char (不能?)或String的多维数组。

Text file containing below two lines 2x10 : 文本文件包含以下两行2x10:

abcd  x/@#
% addk a 2

I want the array slots to either contain the empty space or at least a replace it with pre-defined character. 我希望数组插槽包含空白空间或至少将其替换为预定义字符。

BufferedReader br = new BufferedReader(new FileReader("files/myFile.txt"));
for(int i=0; i<2; ++i)
{
    for(int j=0; j<10; ++j)
    {
        chars[i][j] = br.readLine().charAt(j);

    }
}

String's toCharArray() will likely solve your problem. 字符串的toCharArray()可能会解决您的问题。 Call it on each line read and feed it into each row of your array of char[][]. 在读取的每一行上调用它,并将其输入到char [] []数组的每一行中。

// in constants declaration
public final static int ROWS = 2;
public final static int COLS = 10;

// somewhere else in your code.
char[][] chars = new char[ROWS][COLS];

// making sure to catch exceptions with opening and reading file
BufferedReader br = new BufferedReader(new FileReader("files/myFile.txt"));

for(int i = 0; i < ROWS; ++i) {
  String line = br.readLine();

  // check line exists, has a length of COLS, else throw exception.

  chars[i] = line.toCharArray();
}

ROWS and COLS are program constants, and you'd better make darn sure that these numbers are correct, else this code will go down in flames. ROWS和COLS是程序常数,您最好确保这些数字正确无误,否则该代码将一发不可收拾。 Better to use List<List<Character>> perhaps. 最好使用List<List<Character>>

您的代码中包含一个错误,每次使用br.readLine()都会读取一条新行,因此将br.readLine()移至外循环并使用此字符串在位置j处查找char。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM