我如何计算 Smalltalk 中已处理字符串的数量?
How can i count the number of processed strings in Smalltalk?
我的程序计算处理过的字符串的字母数。我也想计算字符串的数量,但我不知道如何计算,我还没有在 google 中找到任何有用的东西。感谢您的耐心等待。
|s b|
b := Bag new.
[s := stdin nextLine. s ~= 'exit'] whileTrue: [
s do: [:c |
b add: c.
].
].
b displayNl.
据我所知,您想计算字符串集合中字母出现的次数。首先,我建议您不要在客户打字时这样做(除非您真的需要立即做出反应)。
现在假设您将所有输入收集到一个名为 input
的变量中。要获得出现次数,您只需执行 input asBag
,这会将字符串(字符集合放入一个包中)进行转换。所以现在你已经完成了你的第一个任务。然后就看你认为是什么词了。例如,您可以使用 input substrings
将大字符串分成小字符串,使用白色 space(制表符、space、换行符等)作为分隔符。否则,您可以使用 input substrings: ','
指定要使用的分隔符(在示例中为逗号)。现在要计算字符串中单词的出现次数,您可以使用 input substrings asBag
.
当然,如果你想在用户输入数据时这样做,你可以这样做:
|line characters words|
characters := Bag new.
words := Bag new.
[ line := stdin nextLine. line ~= 'exit'] whileTrue: [
characters addAll: line.
words addAll: line substrings
].
characters displayNl.
words displayNl
如果你想计算从标准输入读取的行数,你可以像在任何命令式语言中那样做:使用计数器。
| numberOfLines s |
numberOfLines := 0.
[s := stdin nextLine. s ~= 'exit'] whileTrue: [
numberOfLines := numberOfLines + 1.
"..."].
numberOfLines displayNl.
或者,按照 Uko 的回答,将所有行收集到另一个集合中,然后使用它的大小:
| lines s |
lines := OrderedCollection new.
[s := stdin nextLine. s ~= 'exit'] whileTrue: [lines add: s. "..."].
lines size displayNl.
我的程序计算处理过的字符串的字母数。我也想计算字符串的数量,但我不知道如何计算,我还没有在 google 中找到任何有用的东西。感谢您的耐心等待。
|s b|
b := Bag new.
[s := stdin nextLine. s ~= 'exit'] whileTrue: [
s do: [:c |
b add: c.
].
].
b displayNl.
据我所知,您想计算字符串集合中字母出现的次数。首先,我建议您不要在客户打字时这样做(除非您真的需要立即做出反应)。
现在假设您将所有输入收集到一个名为 input
的变量中。要获得出现次数,您只需执行 input asBag
,这会将字符串(字符集合放入一个包中)进行转换。所以现在你已经完成了你的第一个任务。然后就看你认为是什么词了。例如,您可以使用 input substrings
将大字符串分成小字符串,使用白色 space(制表符、space、换行符等)作为分隔符。否则,您可以使用 input substrings: ','
指定要使用的分隔符(在示例中为逗号)。现在要计算字符串中单词的出现次数,您可以使用 input substrings asBag
.
当然,如果你想在用户输入数据时这样做,你可以这样做:
|line characters words|
characters := Bag new.
words := Bag new.
[ line := stdin nextLine. line ~= 'exit'] whileTrue: [
characters addAll: line.
words addAll: line substrings
].
characters displayNl.
words displayNl
如果你想计算从标准输入读取的行数,你可以像在任何命令式语言中那样做:使用计数器。
| numberOfLines s |
numberOfLines := 0.
[s := stdin nextLine. s ~= 'exit'] whileTrue: [
numberOfLines := numberOfLines + 1.
"..."].
numberOfLines displayNl.
或者,按照 Uko 的回答,将所有行收集到另一个集合中,然后使用它的大小:
| lines s |
lines := OrderedCollection new.
[s := stdin nextLine. s ~= 'exit'] whileTrue: [lines add: s. "..."].
lines size displayNl.