将每个元素行放入java中的数组中

时间:2017-01-07 14:44:45

标签: java arrays string split

我有一个txt文件,我需要将行的每个元素(字符串,空格)放到数组中。

示例:

1行"嘿,1天\ n"

2 /// etc

第一行的输出:[" H" " E" " Y" "" " " " 1" " d" "" " Y"]

这样做的最佳方式是什么?使用split和string还是可以在char类型上运行?

1 个答案:

答案 0 :(得分:2)

为什么不在字符串上调用String#toCharArray

如果您使用nextLine,读者将截断换行符。

类似的东西:

try(BufferedReader r = new BufferedReader(new FileReader("topSecretDocs.txt"))) {
    for(String line = r.readLine(); line != null; line = r.readLine()) {
        char[] chars = line.toCharArray();
        System.out.println("Split line to " + Arrays.toString(chars));
    }
} catch(IOException e) {
    dealWithException();
}

编辑请注意,您可能希望使用String#charAt来遍历字符串,因为无需复制字符数组,尤其是对于非常大的字符串。

编辑2:这是一个非常糟糕的基准。

static long time(Runnable r) {
    long start = System.nanoTime();
    r.run();
    return System.nanoTime() - start;
}

static int cs = 0;

public static void main(String[] args) {
    char[] bigString = new char[100000];
    Arrays.fill(bigString, 0, bigString.length / 4, 'A');
    Arrays.fill(bigString, bigString.length / 4, bigString.length / 2, 'B');
    Arrays.fill(bigString, bigString.length / 2, bigString.length * 3 / 4, 'C');
    Arrays.fill(bigString, bigString.length * 3 / 4, bigString.length, 'D');
    String s = new String(bigString);
    float avgCopy = 0, avgLoop = 0;
    final int times = 100000;
    for(int i = 0; i < times; i++) {
        avgLoop += time(() -> {
            cs = 0;
            for(int j = 0; j < s.length(); j++)
                cs += s.charAt(j) == 'C' ? 1 : 0;
        });
    } avgLoop /= times;
    for(int i = 0; i < times; i++) {
        avgCopy += time(() -> {
            char[] chars = s.toCharArray();
            cs = 0;
            for(char c : chars)
                cs += c == 'C' ? 1 : 0;
        });
    } avgCopy /= times;
    System.out.println("copy: " + avgCopy + " ns");
    System.out.println("loop: " + avgLoop + " ns");
    System.out.println("There were (obviously) " + cs + " Cs in that string.");
}

我明白了:

copy: 70984.336 ns
loop: 40534.63 ns

所以,快一半左右。无论您是否愿意称这是一个重要的差异,我都会留给您。