java - 替换存储在字符串数组中的换行符

标签 java arrays string

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/

相关文章:

c# - 循环图像数组

c++ - 读取一些整数然后在 C++ 中读取一行文本

r - 在单词的字母之间插入空格

java - Spring 交易 : What will happen if I don't give @Transaction annotation on method

java - jaxb注解不可扩展的原因是什么?

javascript - 在 javascript 中的对象数组中搜索深度嵌套的值

sql - 在 PostgreSQL 中使用 json 数组中的索引

python - 根据其他列的文本字符串的开头创建新的 pandas 列

java - Apache Derby 中找不到数据库错误

java - 为什么我在创建新的 Eclipse Android 项目时遇到错误?