MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to count Char, Word and Line in a Textbox using ASP.Net and Csharp

In this article we will cover how to count chars, words and lines in given input string (textbox). This article will use ASP.Net and C# to implement the logic and will cover the basic functionality of count chars, words and lines in a textbox.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Introduction:

This article will cover how to count number of characters in given input text. The article will also count the number of words and Lines. We will cover Counting of char with whitespaces as well as without whitespaces.

This article will cover the following topics:

  • ASP.NET - Script
  • Char Count With Whitespace
  • Char Count Without Whitespace
  • Word Count
  • Line Count
Char Count Screen with Count and Clear Button

Figure 1: Char Count Screen with Count and Clear Button

ASP.NET Script:

We are using ASP.NET page here to interact with user and take the input string and display the output on the screen. The ASP.Net page has some controls, let’s discuss one by one

Textbox: The TextBox is added on the page to take the input string from the user. Note that this is multiline Textbox, It means a user can enter the multiple lines of text. To convert a normal Textbox to multiline Textbox use the TextMode="MultiLine".

Label: The Labels are added here to display the count of chars/words. Note that the Labels should be server side controls otherwise you will not be able to access in C# code.

Button: ASP.NET buttons are used here to perform count and clear functionality on the page.

Listing 1: ASP.NET Script for Char Count

<head runat="server">
    <title>MrBool.com - Char/Word Count Article</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Input Text:<br />
 <asp:TextBox TextMode="MultiLine" ID="txtCharInput" runat="server" Height="164px" 
            Width="400px"></asp:TextBox> 
        <br />
        <br />
        Total Char Count:
        <asp:Label ID="lblTotalCharCount" runat="server" Text=""></asp:Label>
        <br />
        <br />
        Char Count Without Whitespace:
        <asp:Label ID="lblCharCountWithoutWhitespace" runat="server" Text=""></asp:Label>
        <br />
        <br />
        Word Count:
        <asp:Label ID="lblWordCount" runat="server" Text=""></asp:Label>
        <br />
        <br />
        Line Count:
        <asp:Label ID="lblLineCount" runat="server" Text=""></asp:Label>
        <br />
        <br />
         <asp:Button ID="btnCount" runat="server" Text="Count" 
            onclick="btnCount_Click" />
     <asp:Button ID="btnClear" runat="server" Text="Clear" 
            onclick="btnClear_Click" />
    </div>
    </form>
</body>

C# Code:

All counting logic is written in C#. So let’s discuss it one by one. Before starting let’s add the required namespaces, we will use the regular expression here so add the namespace for that:

Listing 2: Namespaces for Count Operations

using System;
using System.Text.RegularExpressions;

Let’s write the code for page load event, Here just assign the count to 0 for each type of counting.

Listing 3: Page Load Event

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lblTotalCharCount.Text = "0";
            lblCharCountWithoutWhitespace.Text = "0";
            lblWordCount.Text = "0";
            lblLineCount.Text = "0";
        }
    } 

Char Count With Whitespace:

To modularize the program, we have added each functionality in different methods. CountTotalChars is written here to count the char with WhiteSpace.

Char counting logic is very simple in this case. Loop through each char of a given string and increase the char count variable every time. Note that it may be possible that char count is very large, so use long type of variable to hold total number count.

Figure 2 shows the output of this code snippet. Total characters in given input text is 13 in this case.

Char count with whitespace

Figure 2: Char count with whitespace.

Listing 4: C# code to count total Number of characters

private long CountTotalChars(string strInput)
    {
        long intCount = 0;
        
        foreach (char ch in strInput)
        {                
           intCount++;                            
        }
        return intCount;
    }

Char Count Without Whitespace:

Char count without whitespace does not count the whitespace chars (Blank chars) while counting. Its similar to previous counting but you have to add one condition for this. First loop through all the chars in input string and then add a condition to check that if there is a whitespace don’t increase the counter.

Char struct provides a static method “IsWhiteSpace”. This method return true if given char is a blank space.

Listing 5: C# Code to count char without whitespace

private long CountCharsWithoutWhitespace(string strInput)
    {
        long intCount = 0;
        
        foreach (char ch in strInput)
        {
            if(!char.IsWhiteSpace(ch))
                intCount++;                
            
        }
        return intCount;
    }
 

The below example explains everything. The total chars are 30, there is 3 whitespaces in between so it is showing char count without whitespace equal to 27.

Char count without whitespace

Figure 3: Char count without whitespace

Word Count:

Word count logic is different from other char count logic. Lets start with logic of word count.

Here first you have to find the whitespace, if the previous char is whitespace and current char is Letter, Digit or Punctuation the it is a word and increase the word count by 1. The above logic will not handle the first word. For that add another condition that if input string is having length more than 2, so add increment the counter by 1.

Listing 6: C# Code for Word Count

private long WordCount(string strInput)
    {
        long intCount = 0;
        for (int i = 1; i < strInput.Length; i++)
        {
            if (char.IsWhiteSpace(strInput[i - 1]) == true)
            {
                if (char.IsLetterOrDigit(strInput[i]) == true ||
                    char.IsPunctuation(strInput[i]))
                {
                    intCount++;
                }
            }
        }
        if (strInput.Length > 2)
        {
            intCount++;
        }
        return intCount;
    }
 
Word Count Example

Figure 4: Word Count Example

Line Count:

After using the loop count for char and word, let’s use the regular expression to count lines this time.

Create Regex object with “\n”, “\n” is a new line character. It means if there is a line break an invisible char “\n” will be added there. Now match this char and get count of “\n” in the given string. So suppose we found one “\n” in string it means there will be two lines. So add logic to handle this also.

Listing 7: C# Code for Line Count

private long LineCount(string strInput)
    {        
        Regex regxNewLine = new Regex("\n", RegexOptions.Multiline);
        MatchCollection objMatchCollection = regxNewLine.Matches(strInput);
        
        return objMatchCollection.Count + 1;
    } 

The below example has 3 lines as input and our output is matching with this.

Line Count Example

Figure 5: Line Count Example

Conclusion:

We covered the basic logic to calculate the counts, Because this is ASP.Net page so it will not work for some specials character. You can improve this program and handle all those cases.

Please comment here if have any questions regarding above article.



I am having total 7+ years of experience in developing applications using C#, VB.NET, ASP.NET, Silverlight, WCF, SQL Server and Oracle. I am holding a M.Tech degree in Intelligent systems. For more information, visit my Linkedin p...

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login