160

I have the following:

string test = "9586-202-10072"

How would I get all characters to the right of the final - so 10072. The number of characters is always different to the right of the last dash.

How can this be done?

12 Answers 12

322

You can get the position of the last - with str.LastIndexOf('-'). So the next step is obvious:

var result = str.Substring(str.LastIndexOf('-') + 1);

Correction:

As Brian states below, using this on a string with no dashes will result in the original string being returned.

Additional:

Since the introduction of C# 8 you can rewrite the code to use range indicator:

var result = str[(str.LastIndexOf('-') + 1)..];
4
  • 2
    This works even when the hyphen is the last character, in that case it correctly returns an empty string. This will only fail if either str is null or if it doesn't contain a hyphen at all. (In the case where there's no hyphen it doesn't throw; it returns the entire source string.)
    – LukeH
    Mar 16, 2011 at 15:31
  • @LukeH: Thanks for the heads up. I didn't check and mistakenly assumed it would throw.
    – Jon
    Mar 16, 2011 at 15:33
  • 3
    Well, LastIndexOf returns -1 if nothing is found (this is documented behavior, so it is safe to rely on it). str.Substring(1-1) gives you a string equal to str. No surprises, here.
    – Brian
    Mar 16, 2011 at 18:55
  • 3
    @Brian: I think I broke my record for most mistakes in the same trivial statement. Lesson: don't ever write anything without proofreading the code after the fact. Thanks.
    – Jon
    Mar 16, 2011 at 19:00
75

You could use LINQ, and save yourself the explicit parsing:

string test = "9586-202-10072";
string lastFragment = test.Split('-').Last();

Console.WriteLine(lastFragment);
1
  • 6
    This will probably save the most developer time, but in the general case note that code like this will many string allocations (probably four in the example above) so might be deemphasized in performance-critical sections. Mar 21, 2016 at 16:05
6

I can see this post was viewed over 46,000 times. I would bet many of the 46,000 viewers are asking this question simply because they just want the file name... and these answers can be a rabbit hole if you cannot make your substring verbatim using the at sign.

If you simply want to get the file name, then there is a simple answer which should be mentioned here. Even if it's not the precise answer to the question.

result = Path.GetFileName(fileName);

see https://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx

4
string tail = test.Substring(test.LastIndexOf('-') + 1);
4
YourString.Substring(YourString.LastIndexOf("-"));
1
  • 7
    if you exclude "+ 1" at the end, then the output will contain special character along with the string.
    – Meena
    Sep 1, 2016 at 6:28
4

With the latest C# 8 and later you can use Range Indexer as follows:-

string test = "9586-202-10072"

var foo = test?[(test.LastIndexOf('-') + 1)..];

// foo is => 10072
2
string atest = "9586-202-10072";
int indexOfHyphen = atest.LastIndexOf("-");

if (indexOfHyphen >= 0)
{
    string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
    Console.WriteLine(contentAfterLastHyphen );
}
1

See String.lastIndexOf method

1

I created a string extension for this, hope it helps.

public static string GetStringAfterChar(this string value, char substring)
    {
        if (!string.IsNullOrWhiteSpace(value))
        {
            var index = value.LastIndexOf(substring);
            return index > 0 ? value.Substring(index + 1) : value;
        }

        return string.Empty;
    }
1
test.Substring[(test.LastIndexOf('-') + 1)..]

C# 8 (late 2019) introduces range operator and simplifies it a bit further. The two dots here means from the index (inclusive) till the end of string.

1
  • I was about to post the same for some easy reputation, after VS suggested me this refactor. But you were first; here you go, upvoted. :P
    – Leaky
    Mar 16, 2022 at 17:22
0

test.Substring(test.LastIndexOf("-"))

0

and... in case you need the left part of a string:

private string AllTheLeftPart(string theString)
{       
    string rightPart = theString.Substring(theString.LastIndexOf('-') + 1);

    string leftPart theString.Replace("-" + rightPart, String.Empty);

    return leftPart ;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.