tags:

views:

315

answers:

4

Hi, 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. 
        }
+6  A: 
string sub = input.Substring(input.Length - 5);
KennyTM
+1 for being first. :)
Blair Holloway
@KennyTM, Thanks for your quickly reply. :-)
Nano HE
I don't understand why people give score to the first answers. The purpose of scrore system is not to be a speed contest, but to show which answer is the best. This and some other answers have the problem that there is no check for string length.
PauliL
+2  A: 

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
+16  A: 

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
@Mark, 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
@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
+3  A: 

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