OneBite.Dev - Coding blog in a bite size

Count A String Length In C#

Code snippet for how to Count A String Length In C# with sample and detail explanation

Every programming language gives us the ability to manipulate strings in different ways, and C# is no exception. In this article, we will walk through how to count a string length in C# using a simple code snippet and then explain how the different parts of the code work.

Code snippet to count a string length

Here is a simple C# code snippet that counts the length of a string.

using System;

class Program
{
    static void Main()
    {
        string str = "HelloWorld!";
        int length = str.Length;
        Console.WriteLine("Length of the String is " + length);
    }
}

When you run this program, it will output:

Length of the String is 11

Code Explanation for counting a string length

Let’s break down the code step by step.

using System;

This is a using directive, which allows us to use the classes in the System namespace without specifying their full names.

class Program

This line of the code declares a class named Program. A class is a blueprint for creating objects (a particular data structure), providing initial values for member variables or methods.

static void Main()

This line defines the Main method, which is the entry point for a C# console application.

string str = "HelloWorld!";

This line declares a string variable called str and initializes it with the value “HelloWorld!“.

int length = str.Length;

This line of code uses the Length property of the string class in C#. The Length property returns the number of characters in the string — in this case, “HelloWorld!“. The length of this string is 11, which is then stored in the variable called length.

Console.WriteLine("Length of the String is " + length);

In the end, the Console.WriteLine method is called to print the length of the string in the console.

Now you know how to count a string length in C# using the Length property of the string class. This method should work for any string, regardless of its content or length. Try it with different string values and see the result for yourself.

c-sharp