We can get the length of a string using the .Length property 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.
Free plan: 30 tutor messages. PRO is unlimited.
