Re: Number of Words in a String

*To*: mathgroup at smc.vnet.net*Subject*: [mg102536] Re: Number of Words in a String*From*: pfalloon <pfalloon at gmail.com>*Date*: Wed, 12 Aug 2009 04:37:20 -0400 (EDT)*References*: <h5r8b5$l4q$1@smc.vnet.net>

On Aug 11, 5:58 pm, Gregory Lypny <gregory.ly... at videotron.ca> wrote: > Hello everyone, > > Is this the simplest way to find the number of words in a string? > Seems a little complicated, and I can't seem to turn it into a > function because when I replace the string with the argument > placeholder myString_ I get an error message saying that a string is > expected in that spot. > > Length[ReadList[StringToStream["The cat in the hat."], Word]] > > Returns 5. > > Gregory were you using Set ( a = b) rather than SetDelayed (a := b) in your function definition? The following works for me: In[12]:= f[str_] := Length[ReadList[StringToStream[str], Word]] f["hey there"] Out[13]= 2 However, it's much quicker to use the StringSplit function: In[14]:= Length@StringSplit["hey there"] Out[14]= 2 In[19]:= Do[f["hey there"],{5000}] // AbsoluteTiming Out[19]= {5.1405921,Null} In[21]:= Do[Length@StringSplit["hey there"],{5000}] // AbsoluteTiming Out[21]= {0.0156249,Null} Cheers, Peter.