Count Number of Words using C#

This is a tutorial in which we will going to create a program that will count the number of words that we have inputted using C#. Now, let's start this tutorial! 1. Let's start with creating a Windows Form Application in C# for this tutorial by following the following steps in Microsoft Visual Studio: Go to File, click New Project, and choose Windows Application and name your project as Word Count Program. 2. Next, add one RichTextBox named RichTextBox1 and a Button named Button1 labeled as "Get Number of Words". You must design your interface like this below: design 3. Now put add this code for your code module. This code is for Button1_Click. This will trigger to count the number of words in your RichTextBox. Initialize variable strInput as String to hold the value inputted in the RichTextBox.
  1. string strInput = default(string);
  2. strInput = RichTextBox1.Text;
Declare variable strSplit as string to split the words inputted in the RichTextBox. We use to split the words inputted to find the spacing of the text. so, that's how we count the words. Then we create a MessageBox to display the number of words using the Length function.
  1. string[] strSplit = null;
  2. strSplit = strInput.Split(' ');
  3. MessageBox.Show("Number of words: " + strSplit.Length);
Full Source code:
  1. using System.Diagnostics;
  2. using System;
  3. using System.Windows.Forms;
  4. using System.Collections;
  5. using System.Drawing;
  6. using System.Data;
  7. using System.Collections.Generic;
  8.  
  9.  
  10.  
  11. namespace Word_Count_Program
  12. {
  13.         public partial class Form1
  14.         {
  15.                 public Form1()
  16.                 {
  17.                         InitializeComponent();
  18.                 }
  19.                
  20.                
  21.                 public void Button1_Click(System.Object sender, System.EventArgs e)
  22.                 {
  23.                         string strInput = default(string);
  24.                         strInput = RichTextBox1.Text;
  25.                         string[] strSplit = null;
  26.                         strSplit = strInput.Split(' ');
  27.                         MessageBox.Show("Number of words: " + strSplit.Length);
  28.                 }
  29.         }
  30.        
  31. }
Output: output Download the source code and try it! Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment