Mailing List Archive: 49091 messages
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search

[REBOL] Re: count characters. (Was: Simple things should be simple to do ?)

From: brett:codeconscious at: 16-Nov-2000 20:22

> So, let's see if anyone else comes up with even more elegant solutions. I > love to see other people's code. The ideas some people come up with never > stop to astound and delight me.
I won't claim my solution to be any more elegant, but just shows another way of looking at the problem. I limit my solution to only handling strings and I know at that Rebol at the moment only has 8bit characters. So I can map characters to array positions. So the counting part becomes the smallest part of the code and potentially the fastest bit. The array structure might be a useful result if you were doing some sort of batch analysis so I leave it available to be returned using a refinement. character-count: function [ "Counts characters in a string." string [string!] /positional "Return an array of counts - position indicates character." ] [count-array slot c result-block char-count] [ ; Do the counting count-array: array/initial 256 0 foreach c string [ slot: add 1 to-integer c poke count-array slot (add 1 pick count-array slot) ] ; Returns the result in desired format either positional [ RETURN count-array ] [ result-block: copy [] for i 1 256 1 [ if greater? c: pick count-array i 0 [ insert tail result-block reduce [to-char subtract i 1 c] ] ] RETURN result-block ] ] Example
>> str: "sdfsdfsdfsdfsdfsd"
== "sdfsdfsdfsdfsdfsd"
>> print mold character-count str
[#"d" 6 #"f" 5 #"s" 6] Regards Brett