Start learning free

LESSON 58 OF 347 · STRINGS I

String Length in C#: The Length Property

Lesson Read the full explanation

We can get the length of a string using the .Length method like this:

string message = "Hello world";

// Printing the length:
Console.WriteLine(message.Length); // Output: 11

// Changing the message:
message += "!";

// Printing the new length:
Console.WriteLine(message.Length); // Output: 12

Accessing characters from the end:

The length is useful for accessing characters from the end of a string.

Because strings are 0-indexed, the index of the last character is length - 1:

string message = "Hello world";
int length = message.Length;

// Printing the last character:
Console.WriteLine(message[length - 1)); // Output: d

// Printing the second to last character:
Console.WriteLine(message[length - 2)); // Output: l

In general, if you want the nth last character, you use message[length - n).


Slicing characters from the end:

The length is also useful for slicing some characters from the end of a string:

string message = "Hello world";
int length = message.Length;

// Slicing last 4 characters:
string lastChars = message.Substring(length - 4);
Console.WriteLine(lastChars); // Output: orld

// Slicing last 7 characters:
lastChars = message.Substring(length - 7);
Console.WriteLine(lastChars); // Output: o world

In general, if you want the last n characters, you use message.Substring(length - n).


Assignment
Follow the Coding Tutorial and let's practice with string length!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    C# · STRINGS I

    String Length in C#, explained

    Getting the length

    Every string has a Length property that holds the number of characters in it. In C#, Length is a property, not a method, so you write it without parentheses:

    string message = "Hello world";
    
    Console.WriteLine(message.Length);  // 11
    
    message += "!";
    Console.WriteLine(message.Length);  // 12
    

    The space counts as a character, which is why "Hello world" has 11. An empty string "" has a length of 0. Writing message.Length() is an error, because a property is not something you can call. Code from languages where length is a method often makes this mistake.

    The += line builds a new, longer string and stores it in message, since strings cannot be edited in place. The new string has a new length.

    Counting from the end

    Indexes start at 0, so the first character is at index 0 and the last one is at index Length - 1. That makes the length the key to reaching the end of a string:

    string message = "Hello world";
    int length = message.Length;
    
    Console.WriteLine(message[length - 1]);  // d
    Console.WriteLine(message[length - 2]);  // l
    

    In general, the n-th character from the end is message[message.Length - n]. C# has no negative indexes like message[-1]; using one throws an IndexOutOfRangeException. Newer C# does offer message[^1] for the last character, but this lesson sticks to the Length - n form that works everywhere.

    Slicing from the end

    The same trick helps with Substring. To take the last n characters, start at Length - n:

    string message = "Hello world";
    int length = message.Length;
    
    Console.WriteLine(message.Substring(length - 4));  // orld
    Console.WriteLine(message.Substring(length - 7));  // o world
    

    With only a start index, Substring runs to the end of the string. If you also pass a length, remember it is a character count, not an end index: message.Substring(length - 4, 4) gives the same orld.

    Using Length in loops

    The length is also the natural limit of a loop over a string. The loop runs while the index is below Length, so it visits indexes 0 to Length - 1 and stops:

    string word = "abc";
    
    for (int i = 0; i < word.Length; i++) {
        Console.Write(word[i] + "-");
    }
    // a-b-c-
    

    Going backwards starts at the last index instead: for (int i = word.Length - 1; i >= 0; i--) visits c, b, a.

    What Length counts

    Length counts char values, which are the 16-bit units a C# string is made of. For everyday text that is the same as the number of visible characters. Escape sequences such as "\n" count as one character, so "a\nb" has length 3. A few rare symbols, such as some emoji, take two units, so "😀".Length is 2.

    Empty strings

    A string with no characters has a length of 0, and a string of spaces has the length of its spaces. To test for "nothing there" you can compare the length to 0, or use the built-in helper:

    string empty = "";
    string spaces = "  ";
    
    Console.WriteLine(empty.Length == 0);               // True
    Console.WriteLine(string.IsNullOrEmpty(empty));     // True
    Console.WriteLine(spaces.Length);                   // 2
    

    A string variable can also be null, which means it refers to no string at all. Reading .Length on a null variable throws a NullReferenceException, while string.IsNullOrEmpty handles both cases safely.

    The exercise, step by step

    The lesson uses message = "I love pancakes", which has 15 characters, so its valid indexes run from 0 to 14.

    1. Print the length. message.Length gives 15, and Console.WriteLine prints it.
    2. Print the last character. The last index is message.Length - 1, which is 14. The character there is s.
    3. Print the last five characters. They start at index message.Length - 5, which is 10, and there are 5 of them. The text is cakes.
    string message = "I love pancakes";
    
    Console.WriteLine(message.Length);
    Console.WriteLine(message[message.Length - 1]);
    Console.WriteLine(message.Substring(message.Length - 5, 5));
    

    The output is:

    15
    s
    cakes
    

    Common mistakes

    • Using message[message.Length]. That index is one past the last character and throws an IndexOutOfRangeException. The next lesson looks at this in detail.
    • Forgetting the - 1. The length is a count; the last index is one less.
    • Adding parentheses to Length. It is a property, so Length() does not compile.
    • Taking the length of an empty string and indexing it. "".Length is 0, so Length - 1 is -1, and indexing with it throws. Check for an empty string first when it can happen.

    Key takeaways

    • Length is a property with no parentheses and counts every character, spaces included.
    • The last valid index is Length - 1.
    • The last n characters start at Length - n.
    • Strings are immutable, so a changed string has a new length and lives in a new object.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free