如何找到给定字符串中的单词数?
How can I find the number of words in a given string?
我想在 Pascal 中查找给定字符串中的单词数?
这是我的入门课程:
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.
您可以将程序实现为 finite-state machine 具有两种状态(“字内”和“字分隔符”):
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.
这是一个将每个 non-letter 视为单词分隔符的解决方案:
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.
在 Free Pascal 中,strutils 单元中有一个 wordcount 函数:
uses strutils;
var s : string;
begin
write('Enter a string: '); readln(s);
writeln('Number of words: ',wordcount(s,[' ','.',',']));
end;
我想在 Pascal 中查找给定字符串中的单词数?
这是我的入门课程:
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.
您可以将程序实现为 finite-state machine 具有两种状态(“字内”和“字分隔符”):
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.
这是一个将每个 non-letter 视为单词分隔符的解决方案:
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.
在 Free Pascal 中,strutils 单元中有一个 wordcount 函数:
uses strutils;
var s : string;
begin
write('Enter a string: '); readln(s);
writeln('Number of words: ',wordcount(s,[' ','.',',']));
end;