Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Don't count spaces when counting words.

, 6 Dec 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
This is less expensive:For any of the next strings, it gives 8:"Mr O'Brien-Smith arrived at 8.30 and spent \t $1,000.99"" Mr O'Brien-Smith arrived at 8.30 and spent \t $1,000.99""Mr O'Brien-Smith arrived at 8.30 and spent \t $1,000.99 "" Mr O'Brien-Smith arrived at 8.30 and...

This is less expensive:

For any of the next strings, it gives 8:

  • "Mr O'Brien-Smith arrived at 8.30 and spent \t $1,000.99"
  • " Mr O'Brien-Smith arrived at 8.30 and spent \t $1,000.99"
  • "Mr O'Brien-Smith arrived at 8.30 and spent \t $1,000.99 "
  • " Mr O'Brien-Smith arrived at 8.30 and spent \t $1,000.99 "
public static int CountWords(string psString)
{
    int nCount = 0;
    if (psString != null)
    {
        int nLength = psString.Length;
        if (nLength > 0)
        {
            bool lInWhite = true;
            for (int nCurrent = 0; nCurrent < nLength; nCurrent++)
            {
                if (char.IsWhiteSpace(psString[nCurrent]) != lInWhite)
                {
                    if (lInWhite == false)
                        nCount++;
                    lInWhite = lInWhite == false;
                }
            }
            if (lInWhite == false)
                nCount++;
        }
    }
    return nCount;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

FDW

Netherlands Netherlands
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150301.1 | Last Updated 6 Dec 2011
Article Copyright 2011 by FDW
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid