get all characters to right of last dash

前端 未结 9 388
遇见更好的自我
遇见更好的自我 2020-12-07 13:50

I have the following:

string test = \"9586-202-10072\"

How would I get all characters to the right of the final - so 10072. Th

相关标签:
9条回答
  • 2020-12-07 14:04
    string atest = "9586-202-10072";
    int indexOfHyphen = atest.LastIndexOf("-");
    
    if (indexOfHyphen >= 0)
    {
        string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
        Console.WriteLine(contentAfterLastHyphen );
    }
    
    0 讨论(0)
  • 2020-12-07 14:06

    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;
        }
    
    0 讨论(0)
  • 2020-12-07 14:10

    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 same string being returned.

    0 讨论(0)
  • 2020-12-07 14:11
    YourString.Substring(YourString.LastIndexOf("-"));
    
    0 讨论(0)
  • 2020-12-07 14:16

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

    string test = "9586-202-10072";
    string lastFragment = test.Split('-').Last();
    
    Console.WriteLine(lastFragment);
    
    0 讨论(0)
  • 2020-12-07 14:16

    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

    0 讨论(0)
提交回复
热议问题