How to Count Number of Words in C# string?
It is always a good practise to restrict user inputs in the form of validations in any application we develop. One such thing is restricting users to type or allow only certain number of words in a input box. This little article will help you to count the number of words in a given string which you can use to restrict the number of words in these scenarios.
The string class has a method called Split() which can split a string using the character/string(sort of delimiter) passed as argument. This method will return a string array by splitting original string wherever the delimiter occurs.
To get number of words in a string, we can use this method to split the string based on the occurence of space and other possible characters that can separate the words as splitting condition. The resulting array's length give you the count of the number of words in the string.
This little code snippet will help you to do that. protected void Page_Load(object sender, EventArgs e) { string text = "This is an simple example which demonstrates how to count the number words in a string using C#. To do this, we will use String class and Split method."; Response.Write(GetNoOfWords(text).ToString()); } public int GetNoOfWords(string s) { return s.Split(new char[] { ' ', '.', ',','?' }, StringSplitOptions.RemoveEmptyEntries).Length; } The above code assumes space, comma, full stop, question mark as word separators and will return the word count.
|