首页 > 解决方案 > 删除文本文件中的空格

问题描述

我必须编写一个简单的代码来计算文本文件中的单词。然后有人告诉我,这是不完整的,因为例如,当连续有 2 个或更多空格时,函数会将它们计为一个单词,结果将不正确。所以我试图通过制作一个列表并删除那里的所有“”元素来修复它,但它似乎不起作用。你能建议可以做什么吗?

这是现在的代码:

    int count = 0;
    File file = new File("C:\\Users\\user\\Desktop\\Test.txt");
    FileInputStream fis = new FileInputStream(file);
    byte[] bytesArray = new byte[(int) file.length()];
    fis.read(bytesArray);
    String s = new String(bytesArray);
    String[] data = s.split(" ");
    List<String> list = new ArrayList<>(Arrays.asList(data));
    list.remove(" ");
    data = list.toArray(new String[0]);
    for (int i = 0; i < data.length; i++) {
        count++;
    }
    System.out.println("Number of words in the file are " + count);

标签: javafileremoving-whitespace

解决方案


您可以通过正则表达式实现这一点

字符串[] 数据 = s.split("\s+");

        int count = 0;
        File file = new File("/home/vahid/Documents/test.txt");
        FileInputStream fis = new FileInputStream(file);
        byte[] bytesArray = new byte[(int) file.length()];
        fis.read(bytesArray);
        String s = new String(bytesArray);
        String[] data = s.split("\\s+");
        List<String> list = new ArrayList<>(Arrays.asList(data));
        list.remove(" ");
        data = list.toArray(new String[0]);
        for (int i = 0; i < data.length; i++) {
            count++;
        }
        System.out.println("Number of words in the file are " + count);

推荐阅读