Search code examples
c#.netsubstring

From end to start how to get everything from the 5th occurence of "-"?


I have this string: abc-8479fe75-82rb5-45g00-b563-a7346703098b

I want to go through this string starting from the end and grab everything till the 5th occurence of the "-" sign.

how do I substring this string to only show (has to be through the procedure described above): -8479fe75-82rb5-45g00-b563-a7346703098b


Solution

  • According to your string rules, I would do a simple split :

    var text = "abc-8479fe75-82rb5-45g00-b563-a7346703098b";
    var split = text.split('-');
    if (split.Lenght <= 5)
       return text;
    return string.Join('-', split.Skip(split.Lenght - 5);