George312
George312

Reputation: 27

How can i count the number of processed strings in Smalltalk?

My program counts the number of the processed strings's letters. I would also like to count the number of string but i have no idea how to, i havent found any useful stuff in google. Thanks for your patience.

|s b|
b := Bag new.

[s := stdin nextLine. s ~= 'exit'] whileTrue: [
    s do: [:c |
        b add: c.
    ].
].

b displayNl.

Upvotes: 1

Views: 679

Answers (2)

JayK
JayK

Reputation: 3141

In case you want to count the number of lines read from stdin, you could do it like in any imperative language: Use a counter.

| numberOfLines s |
numberOfLines := 0.
[s := stdin nextLine. s ~= 'exit'] whileTrue: [
    numberOfLines := numberOfLines + 1.
    "..."].
numberOfLines displayNl.

Or, following Uko's answer, collect all the lines into another collection and use its size afterwards:

| lines s |
lines := OrderedCollection new.
[s := stdin nextLine. s ~= 'exit'] whileTrue: [lines add: s. "..."].
lines size displayNl.

Upvotes: 1

Uko
Uko

Reputation: 13396

So as far as I can tell you want to count the number of occurrences of letters in a collection of strings. First, of all, I'd suggest you not to do that while the client is typing (unless you really need to react immediately).

Now imagine that you gathered all the input into a variable called input. To get the occurrences, you can just do input asBag, and this will convert the string (collection of characters into a bag). So now you have your first task done. Then it depends on what in your opinion is a word. For example, you can use input substrings to break your big string into small ones using whitespace (tab, space, newline, etc…) as a separator. Otherwise, you can use input substrings: ',' where you specify which separator do you want to use (in the example it is a comma). Now to count the occurrences of the words in your string you can use input substrings asBag.

Of course, if you want to do it as a user enters the data you can do something like this:

|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

Upvotes: 2

Related Questions