如何统计给定字符串的单词数?含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 Worldshouldn't count those extra spaces as words) - Multiple consecutive spaces (e.g.,
Hello Worldis 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 Worldhas 1 space, but 2 words—your code outputs 1Hello Worldhas 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
inWordboolean 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
inWordas true. - When we hit a space and were in a word, that means the word has ended—so we mark
inWordas 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
相关产品推荐
相关产品推荐

