Languages
[Edit]
EN

C# / .NET - get last character from string

0 points
Created by:
aaliyah
471

In this article, we would like to show you how to get the last character from a string in C# / .NET.

Quick solution: 

string text = "1234";
string lastCharacter = text.Substring(text.Length - 1);

Console.WriteLine(lastCharacter);  // 4

 

Practical example

The below example shows how to use Substring() method to get the last character from the text string.

using System;

public class StringUtils
{

    public static string getLastCharacters(string text, int charactersCount)
    {
        int length = text.Length;
        int offset = Math.Max(0, length - charactersCount);
        return text.Substring(offset);
    }

    public static void Main(string[] args)
    {
        Console.WriteLine( getLastCharacters( "1234", 1) );  // 4
        Console.WriteLine( getLastCharacters(  "123", 1) );  // 3
        Console.WriteLine( getLastCharacters(   "12", 1) );  // 2
        Console.WriteLine( getLastCharacters(    "1", 1) );  // 1
        Console.WriteLine( getLastCharacters(     "", 1) );  //
    }
}

Output:

4
3
2
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# / .NET - String (popular problems)

C# / .NET - get last character from string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join