Count the number of characters (with and without spaces) and words of an input sentence (C#)

Lets open a new windows form application project and make a window like below :

Now double click on Show button and write down below code :

string input = richTextBox.Text;

For total number of characters : 

txtTotalCharacters.Text = input.Length.ToString();

For total number of characters without spaces : 

            string[] countWithoutSpace = input.Split(null);
int charCountWithoutSpace = 0;
foreach (var word in countWithoutSpace)
{
charCountWithoutSpace += word.Length;
}

txtTotalCharWithoutSpace.Text = charCountWithoutSpace.ToString();

For count the total number of words :

            string[] countWords = input.Split(null);
txtTotalWords.Text = countWords.Length.ToString();

Output :

Now if we run this program and take a sentence as input then we can see the results like below :

Leave a Reply