Possible Duplicate:
How do I compare strings in Java?
考虑以下二维字符串数组 a[5][5],
我将三个值存储在数组“a”的前三个 block 中。 当我打印数组时,我得到以下输出。
ABC
null
DEF
null
这些值存在于文件中,我检索这些值并将它们存储在字符串数组中。
文件(“file.txt”)看起来像这样,
A B C
D E F
这是我的代码,
声明:
static String [][] a= new String [4][4];
public static String newline = System.getProperty("line.separator");
private static int i,j;
主要代码:
i=j=0;
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream (fin);
BufferedReader br = new BufferedReader (new InputStreamReader (in));
while((c = (char)br.read()) != (char)-1)
{
if (c != ' ' && c != (char)'\n')
{
a[i][j] = Character.toString(c);
j++;
}
else if (c == '\n')
{
i++;
j = 0;
}
}
for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
if (newline.equals(a[i][j]))
{
mainArray[i][j] = null;
}
}
}
这是我打印数组的方法,
for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
System.out.print(a[i][j]);
}
System.out.println("");
}
我想要的输出应该是,
ABCnullnull
DEFnullnull
有没有更好的方法来解决这个问题?
最佳答案
BufferedReader 有一个 readLine() 方法,该方法将返回一个字符串,其中包含\n 或\r 之前的所有字符。它还在流末尾返回 null。
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream (fin);
BufferedReader br = new BufferedReader (new InputStreamReader (in));
List<String> list = new ArrayList<String>();
String line;
while ((line= br.readLine())!=null)
{
list.add(line);
}
这将处理任意数量的返回和任意长度的字符串。
或者如果您必须将每一行作为数组
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
List<char[]> list = new ArrayList<char[]>();
String line;
while ((line = br.readLine()) != null) {
if(!line.isEmpty()) list.add(line.toCharArray());
}
读取文件应该会生成一个大小为 2 的列表,每个列表包含 5 个字符的数组。 ['A',' ','B',' ','C'] 然后 ['D',' ','E',' ','F']
关于java - 替换存储在字符串数组中的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12373876/