get all characters to right of last dash

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?


Solution 1:

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.

Solution 2:

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

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

Console.WriteLine(lastFragment);

Solution 3:

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

Solution 4:

string tail = test.Substring(test.LastIndexOf('-') + 1);

Solution 5:

YourString.Substring(YourString.LastIndexOf("-"));