Nano HE Nano HE - 1 year ago 66
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

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 Source

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;
        return input.Substring(input.Length - length);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download