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

瘦欲@ 提交于 2020-12-15 05:39:06

问题


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.

回答1:


You may implement the program as finite-state machine with two states ("inside word" and "word separator"):

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



回答2:


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;



回答3:


Here is a solution which treats every non-letter as a word separator:

PROGRAM P1;

    VAR
        wordCount: Integer;
        insideWord, letterRead: Boolean;
        ch: Char;

BEGIN
    wordCount := 0;
    insideWord := FALSE;
    Write('Enter a string:  ');
    Read(ch);
    WHILE NOT EoLn DO BEGIN
        letterRead := (ch >= 'A') AND (ch <= 'Z') OR (ch >= 'a') AND (ch <= 'z');
        IF NOT insideWord AND letterRead THEN
            Inc(wordCount);
        insideWord := letterRead;
        Read(ch)
    END;
    WriteLn('Number of words: ', wordCount)
END.


来源:https://stackoverflow.com/questions/64611136/how-can-i-find-the-number-of-words-in-a-given-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!