How to get the last five characters of a string using Substring() in C#?

I can get the first three characters with the function below.

However, how can I get the output of the last five characters ("Three") with the Substring() function? Or will another string function have to be used?

static void Main()
{
    string input = "OneTwoThree";

    // Get first three characters
    string sub = input.Substring(0, 3);
    Console.WriteLine("Substring: {0}", sub); // Output One. 
}

Solution 1:

If your input string could be less than five characters long then you should be aware that string.Substring will throw an ArgumentOutOfRangeException if the startIndex argument is negative.

To solve this potential problem you can use the following code:

string sub = input.Substring(Math.Max(0, input.Length - 5));

Or more explicitly:

public static string Right(string input, int length)
{
    if (length >= input.Length)
    {
        return input;
    }
    else
    {
        return input.Substring(input.Length - length);
    }
}

Solution 2:

string sub = input.Substring(input.Length - 5);

Solution 3:

If you can use extension methods, this will do it in a safe way regardless of string length:

public static string Right(this string text, int maxLength)
{
    if (string.IsNullOrEmpty(text) || maxLength <= 0)
    {
        return string.Empty;
    }

    if (maxLength < text.Length)
    {
        return text.Substring(text.Length - maxLength);
    }

    return text;
}

And to use it:

string sub = input.Right(5);

Solution 4:

static void Main()
    {
        string input = "OneTwoThree";

            //Get last 5 characters
        string sub = input.Substring(6);
        Console.WriteLine("Substring: {0}", sub); // Output Three. 
    }
  • Substring(0, 3) - Returns substring of first 3 chars. //One

  • Substring(3, 3) - Returns substring of second 3 chars. //Two

  • Substring(6) - Returns substring of all chars after first 6. //Three