find the last character in a string in csharp

There are a few ways to find the last character in a string in C#. Here are two examples:

Using indexing:

main.cs
string myString = "Hello, world!";
char lastChar = myString[myString.Length - 1];
Console.WriteLine("The last character is: " + lastChar);
139 chars
4 lines

Using substrings:

main.cs
string myString = "Hello, world!";
char lastChar = myString.Substring(myString.Length - 1).ToCharArray()[0];
Console.WriteLine("The last character is: " + lastChar);
166 chars
4 lines

Both methods achieve the same result, which is to find the last character in a given string. In the first example, we use indexing to slice the last character from the string. In the second example, we use the substring method to extract the last character, and then convert it to an array of characters so that we can easily access the last character.

gistlibby LogSnag