如何计算具有多个 space 个字符的文本文件中的所有单词

How to count all the words in a textfile with multiple space characters

我正在尝试编写一个程序来计算 Pascal 文本文件中的所有单词。我想让它处理多个 space 个字符,但我不知道该怎么做。

我尝试添加一个布尔函数 Space 来确定一个字符是否是 space 然后执行

while not eof(file) do
begin    
  read(file,char);
  words:=words+1;
  if Space(char) then
    while Space(char) do
      words:=words;

但这不起作用,基本上只是总结了我(可能是坏的)关于程序应该是什么样子的想法。有什么想法吗?

使用 boolean 变量来指示您是否正在处理单词。

第一个 non-space字符上设置true(并增加计数器)。

在 space 个字符上设置 false

基本上,正如 Tom 在他的回答中概述的那样,您需要一个具有两种状态 In_A_Word 和 Not_In_A_Word 的状态机,然后在您的状态从 Not_In_A_Word 变为In_A_Word.

类似 (pseudo-code) 的内容:

var
  InWord: Boolean;
  Ch: Char;
begin
  InWord := False;
  while not eof(file) do begin    
    read(file, Ch);
    if Ch in ['A'..'Z', 'a'..'z'] then begin
      if not InWord then begin
        InWord := True;
        Words := Words + 1;
      end;
    end else
      InWord := False
  end;
end;

另一种方法是读取一个字符串中的整个文件,然后使用以下步骤计算字数:

{$mode objfpc}
uses sysutils; 

var
  fullstr: string = 'this is   a     test  string. '; 
  ch: char;
  count: integer=0; 

begin 
  {trim string- remove spaces at beginning and end: }
  fullstr:= trim(fullstr); 

  {replace all double spaces with single: }
  while pos('  ', fullstr) > 0 do 
    fullstr := stringreplace(fullstr, '  ', ' ', [rfReplaceAll, rfIgnoreCase]); 

  {count spaces: }
  for ch in fullstr do
    if ch=' ' then 
      count += 1; 

  {add one to get number of words: }
  writeln('Number of words: ',count+1); 
end.

上面代码中的注释解释了这些步骤。

输出:

Number of words: 5