58

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. 
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Nano HE
  • 9,109
  • 31
  • 97
  • 137

12 Answers12

79

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);
    }
}
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Your code works well. But I found it is a little hard to understand. From MSDN. I found **String::Substring Method** included `String.Substring (Int32) ` and `Substring(Int32, Int32)` . Why not include the style like `Substring(fun())`. I think You insert a fun() as a argument for Substring(). Thank you. – Nano HE May 25 '10 at 06:45
  • 2
    @Nano HE: `Math.Max(int, int)` returns the highest of the two numbers passed in. So in this case if `input.Length` is less than 5 characters long `Substring` is passed `0` which effectively gives you the whole of `input`. Otherwise you get a substring of the right 5 characters. – Phil Gan May 25 '10 at 08:10
  • Thank you for this answer! I was running into a very similar issue, and I like how you use the Math functions to get the max length (though I'm using to get the minimum length since the string could be shorter than the length that I was specifying). I kept running into exceptions due to that issue, but your solution is an elegant way to solve that. – Namkce May 29 '19 at 21:21
  • That was fine. I really appreciate. –  Jan 24 '21 at 07:03
14
string sub = input.Substring(input.Length - 5);
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
10

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);
PMN
  • 1,721
  • 13
  • 10
  • 3
    I really hate that this is not how SubString is implemented out of the box. It is very common to call Substring(0,LEN) on a string that is less than LEN, and I always prefer that it just work in that case, not throw a darned exception. I use the Math.Min workaround, but am not happy with it. – Daniel Williams Jul 19 '12 at 20:49
10
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

TylerH
  • 20,799
  • 66
  • 75
  • 101
Mehdi
  • 147
  • 2
  • 9
2

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
Blair Holloway
  • 15,969
  • 2
  • 29
  • 28
2

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));
        }
    }
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Payson Welch
  • 1,388
  • 2
  • 17
  • 29
1

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

anandd360
  • 298
  • 3
  • 14
0

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

Community
  • 1
  • 1
0

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 ? :

WiiMaxx
  • 5,322
  • 8
  • 51
  • 89
0
string input = "OneTwoThree";
(if input.length >5)
{
string str=input.substring(input.length-5,5);
}
ZygD
  • 22,092
  • 39
  • 79
  • 102
hrk1991
  • 3
  • 2
  • 1
    Provided code might help, but in order to make it a good answer you should also describe/explain why/how exactly does your code solve the problem. – ZygD Jun 15 '15 at 19:23
  • yaa... sure.. i ll take care of it @ZygD. – hrk1991 Jun 16 '15 at 17:42
0

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

methos
  • 101
  • 1
  • 5
-2
// 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
TylerH
  • 20,799
  • 66
  • 75
  • 101