I am trying to write a procedure that counts all the words in a text file in Pascal. I want it to handle multiple space characters, but I have no idea how to do it.
I tried adding a boolean function Space to determine whether a character is a space and then do
while not eof(file) do
begin
read(file,char);
words:=words+1;
if Space(char) then
while Space(char) do
words:=words;
but that doesnt work, and basically just sums up my(probably bad) idea about how the procedure should look like. Any ideas?
Basically, as Tom outlines in his answer, you need a state machine with the two states In_A_Word and Not_In_A_Word and then count whenever your state changes from Not_In_A_Word to In_A_Word.
Something along the lines of (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;