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.
- Print the length.
message.Lengthgives 15, andConsole.WriteLineprints it. - Print the last character. The last index is
message.Length - 1, which is 14. The character there iss. - Print the last five characters. They start at index
message.Length - 5, which is 10, and there are 5 of them. The text iscakes.
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 anIndexOutOfRangeException. 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, soLength()does not compile. - Taking the length of an empty string and indexing it.
"".Lengthis 0, soLength - 1is -1, and indexing with it throws. Check for an empty string first when it can happen.
Key takeaways
Lengthis 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.