pascalfreepascalturbo-pascal

How can I find the number of words in a given string?


I'm trying to find the number of words in a given string in Pascal?

This is my starter coede:

Program P1;
 var s:string;
     i,k:integer;
 begin
   write('Enter a string:  '); readln(s);
   k:=0;
   for i:=1 to length(s) do
    begin
        if(s[i] = ' ') then k:=k+1;
    end;
    write('Number of words ', k);
end.

Solution

  • In Free Pascal there is a wordcount function in the strutils unit:

    uses strutils;
    var s : string;
    begin 
      write('Enter a string:  '); readln(s);
      writeln('Number of words: ',wordcount(s,[' ','.',',']));
    end;