You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计给定字符串的单词数?含Pascal语言实现疑问及代码

统计字符串中的单词数量(Pascal实现详解)

Hey there! Let's break down how to count words in a string, and fix up your Pascal code while we're at it.

核心思路:正确统计单词的关键

Counting words isn't just about counting spaces—you have to account for edge cases like:

  • Leading or trailing spaces (e.g., Hello World shouldn't count those extra spaces as words)
  • Multiple consecutive spaces (e.g., Hello World is still 2 words, not 4)
  • Strings with no spaces (a single word) or all spaces (zero words)

The right approach is to track whether you're currently inside a word. Every time you transition from a non-word character (like a space) to a word character, you increment your word count.

What's wrong with your initial Pascal code?

Looking at your code:

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.

This just counts the number of spaces, which leads to wrong results:

  • Hello World has 1 space, but 2 words—your code outputs 1
  • Hello World has 6 spaces, but 2 words—your code outputs 6
  • A single word with no spaces gives 0, which is totally wrong

Fixed Pascal Code

Here's a corrected version that handles all edge cases:

Program P1;
var 
  s:string; 
  i,k:integer;
  inWord:boolean; // Tracks if we're currently inside a word
begin
  write('Enter a string: ');
  readln(s);
  k:=0;
  inWord := false; // Start outside any word
  
  for i:=1 to length(s) do 
  begin
    // Found the start of a new word
    if (s[i] <> ' ') and not inWord then
    begin
      k := k + 1;
      inWord := true;
    end
    // Found the end of the current word
    else if (s[i] = ' ') and inWord then
    begin
      inWord := false;
    end;
  end;
  
  write('Number of words: ', k);
end.

How this works:

  • The inWord boolean keeps track of our current state: are we inside a word or not?
  • When we hit a non-space character and weren't in a word before, that means we've started a new word—so we add 1 to the count and mark inWord as true.
  • When we hit a space and were in a word, that means the word has ended—so we mark inWord as false.
  • This ignores leading/trailing spaces and consecutive spaces, giving you an accurate word count every time.

Test cases to verify:

  • Input: Hello World → Output: 2 ✔️
  • Input: Hello Pascal → Output: 2 ✔️
  • Input: SingleWord → Output: 1 ✔️
  • Input: (all spaces) → Output: 0 ✔️

内容的提问来源于stack exchange,提问作者Iulian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 17:18:14