ID:195074
 
//Title: Word Count
//Credit to: Jtgibson
//Contributed by: Jtgibson


/*
After Hiead teased me about my inefficient word wrapping snippet, I figured
I might as well go ahead and make a word count snippet from scratch using
details I had learned over the past seven or so years. The text2ascii()
proc, introduced only a few years ago, makes a previously complex matter
entirely trivial.

This is an iterative, in-place word count that doesn't replace strings, copy
strings, or do any other playing around. It's blitzingly fast!
*/



proc/wordcount(string)
var/characters = length(string)

//Iterate through the string, toggling state if going from an alphanumeric
// to a non-alphanumeric. "'" is ignored and is considered to be the same
// type as the previous character (e.g., "that's" is one word).
var/alpha = 0
var/wordcount = 0
for(var/i = 1, i <= characters, i++)
switch(text2ascii(string,i))
if(39) continue //apostrophe
if(48 to 57, 65 to 90, 97 to 122) /*0-9, A-Z, a-z*/
//Encountered a new word, increase word count
if(!alpha) {alpha = !alpha; wordcount++}
else
//Word ended -- ignore non-alphanumerics until we encounter another word
if(alpha) {alpha = !alpha}

return wordcount


/*
//Testing code/sample implementation

mob/verb/test_wordcount(string as message)
src << wordcount(string)
*/