Counting Words

Posts 1–5 of 5 · Page 1 of 1
Counting Words
Hey guys I was just wondering If anyone can help me count the words in a textbox in visual basic if you can help that will be great! thanks.
Just loop through the characters of the string and increase a counter for each whitespace which is followed by at least one letter

 
something like this maybe (C#)
Code:
private static int CountWords(string content)
{
  if (string.IsNullOrEmpty(content))
  {
    return 0;
  }

  int count = 0;
  for (int i = 1; i < content.Length; i++)
  {
    if (char.IsWhiteSpace(content[i - 1]) &&
      (char.IsLetter(content[i]) || char.IsPunctuation(content[i])))
    {
      count += 1;
    }
  }
}
Quote Originally Posted by Biesi View Post
Just loop through the characters of the string and increase a counter for each whitespace which is followed by at least one letter

 
something like this maybe (C#)
Code:
private static int CountWords(string content)
{
  if (string.IsNullOrEmpty(content))
  {
    return 0;
  }

  int count = 0;
  for (int i = 1; i < content.Length; i++)
  {
    if (char.IsWhiteSpace(content[i - 1]) &&
      (char.IsLetter(content[i]) || char.IsPunctuation(content[i])))
    {
      count += 1;
    }
  }
}
This is wrong. Other than explicitly returning a 0 if content is null or empty, leaving out you forgot something, you are never returning the number of the words in the sentence. Anyway I prefer doing it in simpler methods:

- using a regex pattern:
Code:
        public static int getWordsCount(string sentence)
        {
            System.Text.RegularExpressions.MatchCollection matchCollection = System.Text.RegularExpressions.Regex.Matches(sentence, @"[\S]+");
            return matchCollection.Count;
        }
- using an one-line and out of the box solution (take it easy):

Code:
sentence.Split(new char[] {'\r', '\n', ' '}, StringSplitOptions.RemoveEmptyEntries).Length;
Solved! Thank you!
Quote Originally Posted by javalover View Post
- using an one-line and out of the box solution (take it easy):
Blaming me for not returning (which I obviously just forgot) but then telling people to create an unnecessarily large array of strings is just bullshit.

Less code does not mean better code tho
Posts 1–5 of 5 · Page 1 of 1
This thread is closed for replies.

Similar Threads

Tags for this Thread

None

Need help?