Home Programs How to get the length of a string in C#

How to get the length of a string in C#

In this example we will create a program that displays the length of a string

The string class has a Length property, which returns the number of characters in its internal buffer. It will return the number of characters in the current string as an Int32.

Table of Contents

Example

In  this example we ask the user to input a string and we will display the length of the string using the Length property

 

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string myString = "";

            Console.Write("Enter a string: ");
            //store user entered string
            myString = Console.ReadLine();
            //display the length of a string
            Console.WriteLine("The length of the string is " + myString.Length);
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
    }
}

Here we show a couple of test runs, in the second one you can see we entered no data and 0 was returned.

Enter a string: test string
The length of the string is 11
Press any key to exit.

Enter a string:
The length of the string is 0
Press any key to exit.

Notes

The length of an empty string is always 0. You can check for an empty string using the IsNullOrEmpty method

A string that uses the “const” modifier also has a length, it is the same as a literal.

The Length property returns the number of Char objects in this instance, not the number of Unicode characters because a Unicode character can be represented by more than one Char

You may also like