C# Count how many chars, words , lines in a string

programmatically count number of words Programmatically count how many chars, word and line in the textbox and list it , first with the help of trim remove unwanted space from start and end of the string. Next count the word as shown in the example and then split string for line count finally count the chars.

Download

Example Source Snippets - WordCounter.zip

namespace :using System.Text.RegularExpressions

Simple word counter


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace WordCounter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();      
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StartCount();
        }

        private void StartCount()
        {
            lblChar.Text = "";
            lblWord.Text = "";
            lblLine.Text = "";

            if (txtUserInput.Text != "")
            {
                string useInput = "";
                useInput = txtUserInput.Text.Trim();             

                string pattern = "[^\\w]";
                string input = useInput;

                //word count             
                int i = 0, count = 0;

               string[] words = Regex.Split(input, pattern, RegexOptions.IgnoreCase);
                for (i = words.GetLowerBound(0); i <=words.GetUpperBound(0); i++)
                {
                    if (words[i].ToString() == string.Empty)
                        count = count - 1;
                    count = count + 1;
                }
                lblWord.Text = count.ToString();

                // line count            
                string[] lines = Regex.Split(useInput.Trim(), "\r\n");                
                lblLine.Text = lines.Length.ToString();

                //char count 
                int CharCount = 0;
                foreach (string value in lines)                
                    CharCount += value.Length;
              
                lblChar.Text = CharCount.ToString();  
            }
        }
    }
}

                 

smartsnipps.ecomparefiles.com © 2019, All Rights Reserved | Disclaimer: smartsnipps.eCompareFiles.com is free to use any code snippets without guarantee