如何从计数中排除空格?

时间:2019-04-01 21:47:18

标签: java

我必须记下文件“ test.txt”中有多少个字母(字符)。我记下来了,但它也包括空格,我不想包括在内。有什么建议吗?非常感谢。

import java.io.*;
class EnglishAnalysis
{
    public static void main(String[] args)
    {
        try
        {
            FileReader fr = new FileReader("test.txt");
            BufferedReader br = new BufferedReader(fr);
            int count = 0;
            String lineCharacters [];
            String line;
            line = br.readLine();
            while (line != null)
            {
                 lineCharacters = line.split("");
                 for (int i = 0; i < lineCharacters.length; i++)
                 {
                     count ++;
                     line = br.readLine();
                 }
                 System.out.println(count);
             }
             br.close();
        }
        catch (IOException e) {}
    }
}

5 个答案:

答案 0 :(得分:2)

或者(对于Java 8+),您可以使用lines()chars()方法很容易地做到这一点:

BufferedReader br = new BufferedReader(fr);
long count = br.lines().flatMapToInt(e -> e.codePoints()).filter(e -> !Character.isWhiteSpace(e)).count();

将提取文件行中的Stream<String>,使用String::codePoints将其平面映射到字符,过滤出所有空白,然后计算元素

答案 1 :(得分:1)

也许我错过了一些东西,但我不知道拆分有什么好处。我会这样做:

public static void main(String[] args) {
    try {
        FileReader fr = new FileReader("/tmp/test.txt");
        BufferedReader br = new BufferedReader(fr);
        int count = 0;
        String line;
        line = br.readLine();
        while (line != null) {
            for (int i = 0; i < line.length(); i++)
                if (!Character.isWhitespace(line.charAt(i)))
                    count++;
            line = br.readLine();
        }
        br.close();
        System.out.println(count);
    } catch (IOException ex) {
        System.out.println(ex);
    }
}

特别是,我认为根本不需要通过调用split,制作额外的副本,执行查找/替换等操作来修改输入。这一切都需要花费额外的时间和空间。

实际上,我看不出任何理由来烦扰文件的处理:

public static void main(String[] args) {
    try {
        FileReader fr = new FileReader("/tmp/test.txt");
        BufferedReader br = new BufferedReader(fr);
        int count = 0;
        while (true) {
            int c = br.read();
            if (c < 0)
                break;
            if (!Character.isWhitespace(c))
                count++;
        }
        br.close();
        System.out.println(count);
    } catch (IOException ex) {
        System.out.println(ex);
    }
}

本身使用BufferedReader可以提高不逐字符读取文件的效率。因此,您可以通过这种方式保存每行的额外副本。

答案 2 :(得分:1)

为什么从所有空格中清除每行后就不添加字符数:

    while (line != null) {
        count += line.replaceAll("\\s+", "").length();
        line = br.readLine();
    }

答案 3 :(得分:0)

为什么在进行分割和计数之前不从字符串中删除空格?

使用正则表达式的一种实现方式:

while (line != null)
{
  line.replaceAll("\\s+","");
  lineCharacters = line.split("");
  ...
}

答案 4 :(得分:0)

角色类具有“ isWhiteSpace()”方法

java.lang.Character.isWhitespace(char ch)

(venv) localhost:mainsite_project davea$ python manage.py migrate mainsite
Operations to perform:
  Apply all migrations: mainsite
Running migrations:
  Applying mainsite.0019_auto_20190401_2139...Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/models/options.py", line 564, in get_field
    return self.fields_map[field_name]
KeyError: 'website'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 203, in handle
    fake_initial=fake_initial,
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/migrations/operations/models.py", line 514, in database_forwards
    getattr(new_model._meta, self.option_name, set()),
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 356, in alter_unique_together
    self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique)
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 379, in _delete_composed_index
    columns = [model._meta.get_field(field).column for field in fields]
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 379, in <listcomp>
    columns = [model._meta.get_field(field).column for field in fields]
  File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/models/options.py", line 566, in get_field
    raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: MainSiteStatByHour has no field named 'website'