65.9K
CodeProject is changing. Read more.
Home

Don't count spaces when counting words.

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Dec 6, 2011

CPOL
viewsIcon

5184

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;
}