Nano HE Nano HE - 21 days ago 7
C# Question

How to get the 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

Substring()
function. Or other string function will be used?

Thank you.

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

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

Answer

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);
    }
}
Comments