【发布时间】:2021-02-16 12:11:46
【问题描述】:
我正在尝试制作记事本克隆,并在状态栏中添加了运行字数统计功能。字数不准确,将重复的空格或回车视为新单词。以下是我尝试过的字数统计功能:
procedure TFormMain.Memo1Change(Sender: TObject);
var
wordSeparatorSet: Set of Char;
count: integer;
i: integer;
s: string;
inWord: Boolean;
begin
wordSeparatorSet := [#13, #32]; // CR, space
count := 0;
s := Memo1.Text;
inWord := False;
for i := 1 to Length(s) do
begin
// if the char is a CR or space, you're at the end of a word; increase the count
if (s[i] in wordSeparatorSet) and (inWord=True) then
begin
Inc(count);
inWord := False;
end
else
// the char is not a delimiter, so you're in a word
begin
inWord := True;
end;
end;
// OK, all done counting. If you're still inside a word, don't forget to count it too
if inWord then
Inc(count);
StatusBar1.Panels[0].Text := 'Words: ' + IntToStr(count);
end;
当然,我愿意接受任何替代方案或改进。我真的不明白为什么这段代码会增加每个空格和回车的字数(count)。我认为在用户按下空格键(递增count)后,变量inWord 现在应该为False,因此如果用户再次按下空格键或Enter 键,if (s[i] in wordSeparatorSet) and (inWord=True) 应该解析为False。但事实并非如此。
【问题讨论】:
-
@AndreasRejbrand 感谢您的回复。我看到了一个或两个你的链接。我已经看到很多我迷路了:-) ...您的“关于您的困惑”的回答非常有帮助。 [有趣的附录:我正要建议你把它写成答案,因为我可能会选择它。你就是这样做的,句子中间。]
-
是的,我意识到我在滥用评论部分! :)
标签: delphi word-count