Services & Resources / Wolfram Forums / MathGroup Archive

MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Number of Words in a String

  • To: mathgroup at
  • Subject: [mg102536] Re: Number of Words in a String
  • From: pfalloon <pfalloon at>
  • Date: Wed, 12 Aug 2009 04:37:20 -0400 (EDT)
  • References: <h5r8b5$l4q$>

On Aug 11, 5:58 pm, Gregory Lypny < at> 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}


  • Prev by Date: Re: Sticky scaling? (for printing)
  • Next by Date: Re: Number of Words in a String
  • Previous by thread: Re: Number of Words in a String
  • Next by thread: Re: Number of Words in a String