Find number of characters in a String using C#

In this article we will discuss about how to find the numbers of characters of the string in C#.
  • 7350

We can use the string.Length property to get the number of characters of a string but it will also count an empty character. So, to find out exact number of characters in a string, we need to remove the empty character occurrences from a string.

The following code snippet uses the Replace method to remove empty characters and then displays the non-empty characters of a string. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "Mahesh Chand";

            // Get size of string
            Console.WriteLine("Size of string: {0}", name.Length);

            // Remove all empty characters
            string nameWithoutEmptyChar = name.Replace(" ", "");

            // Size after empty characters are removed
            Console.WriteLine("Size of non empty char string: {0}",
            nameWithoutEmptyChar.Length);

            // Read and print all characters
            for (int counter = 0; counter <= nameWithoutEmptyChar.Length - 1; counter++)
            Console.WriteLine(nameWithoutEmptyChar[counter]);
            Console.ReadLine();
        }
    }
}
 


Ask Your Question 
 
Got a programming related question? You may want to post your question here
 


Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.