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

C#String

C# Problem Overview


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. 
}

C# Solutions


Solution 1 - C#

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 - C#

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

Solution 3 - C#

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 - C#

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

Solution 5 - C#

One way is to use the Length property of the string as part of the input to Substring:

string sub = input.Substring(input.Length - 5); // Retrieves the last 5 characters of input

Solution 6 - C#

Here is a quick extension method you can use that mimics PHP syntax. Include AssemblyName.Extensions to the code file you are using the extension in.

Then you could call:

input.SubstringReverse(-5) and it will return "Three".

namespace AssemblyName.Extensions {

    public static class StringExtensions
    {
        /// <summary>
        /// Takes a negative integer - counts back from the end of the string.
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        public static string SubstringReverse(this string str, int length)
        {
            if (length > 0) 
            {
                throw new ArgumentOutOfRangeException("Length must be less than zero.");
            }

            if (str.Length < Math.Abs(length))
            {
                throw new ArgumentOutOfRangeException("Length cannot be greater than the length of the string.");
            }
           
            return str.Substring((str.Length + length), Math.Abs(length));
        }
    }
}

Solution 7 - C#

Substring. This method extracts strings. It requires the location of the substring (a start index, a length). It then returns a new string with the characters in that range.

See a small example :

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

Output : Substring: One

Solution 8 - C#

e.g.

string str = null;
string retString = null;
str = "This is substring test";
retString = str.Substring(8, 9);

This return "substring"

C# substring sample source

Solution 9 - C#

simple way to do this in one line of code would be this

string sub = input.Substring(input.Length > 5 ? input.Length - 5 : 0);

and here some informations about Operator ? :

Solution 10 - C#

string input = "OneTwoThree";
(if input.length >5)
{
string str=input.substring(input.length-5,5);
}

Solution 11 - C#

In C# 8.0 and later you can use [^5..] to get the last five characters combined with a ? operator to avoid a potential ArgumentOutOfRangeException.

string input1 = "0123456789";
string input2 = "0123";
Console.WriteLine(input1.Length >= 5 ? input1[^5..] : input1); //returns 56789
Console.WriteLine(input2.Length >= 5 ? input2[^5..] : input2); //returns 0123

index-from-end-operator and range-operator

Solution 12 - C#

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

string sub = input.Substring(6, 5);
Console.WriteLine("Substring: {0}", sub); //You'll get output: Three

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNano HEView Question on Stackoverflow
Solution 1 - C#Mark ByersView Answer on Stackoverflow
Solution 2 - C#kennytmView Answer on Stackoverflow
Solution 3 - C#PMNView Answer on Stackoverflow
Solution 4 - C#MehdiView Answer on Stackoverflow
Solution 5 - C#Blair HollowayView Answer on Stackoverflow
Solution 6 - C#Payson WelchView Answer on Stackoverflow
Solution 7 - C#anandd360View Answer on Stackoverflow
Solution 8 - C#craiglimpoView Answer on Stackoverflow
Solution 9 - C#WiiMaxxView Answer on Stackoverflow
Solution 10 - C#hrk1991View Answer on Stackoverflow
Solution 11 - C#methosView Answer on Stackoverflow
Solution 12 - C#David CahayaView Answer on Stackoverflow