Languages
[Edit]
EN

C# / .NET - get last 3 characters of string

0 points
Created by:
Dirask Admin - Marwin
1430

In this article, we would like to show you how to get the last 3 characters of a string in C#.

Quick solution: 

string text = "This is your text";
string lastThreeCharacters = text.Substring(text.Length - 3);

Console.WriteLine( lastThreeCharacters ); // ext

Practical example

The below example shows how to use .Substring() method to get the last 3 characters of the text string.

using System;

public class Program
{
    static string getLastCharacters(String text, int numberCount)
    {
        if (text.Length == numberCount)
        {
            return text;
        }
        else if (text.Length > numberCount)
        {
            return text.Substring(text.Length - numberCount);
        }
        else
        {
            throw new System.ArgumentException("Your text is to short");
        }
    }
    public static void Main(string[] args)
    {
        Console.WriteLine( getLastCharacters("12345", 3) ); // 345
        Console.WriteLine( getLastCharacters( "1234", 3) ); // 234
        Console.WriteLine( getLastCharacters(  "123", 3) ); // 123
        Console.WriteLine( getLastCharacters(   "12", 3) ); // ERROR: System.ArgumentException: 'Your text is to short'
    }
}

Output: 

345
234
123

C# / .NET - String (popular problems)

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