简体   繁体   中英

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

You can also define handy extension method if that's common use case:

public static class StringExtensions
{
    public static string GetSubstringFromReversedOccurence(this string @this,
        char @char,
        int occurence)
    {
        var indexes = new List<int>();
        var idx = 0;

        while ((idx = @this.IndexOf(@char, idx + 1)) > 0)
        {
            indexes.Add(idx);
        }

        if (occurence > indexes.Count)
        {
            throw new Exception("Not enough occurences of character");
        }

        var desiredIndex = indexes[indexes.Count - occurence];

        return @this.Substring(desiredIndex);
    }
}

We could use a regex replacement with a capture group:

var text = "abc-8479fe75-82rb5-45g00-b563-a7346703098b";
var pattern = @"([^-]+(?:-[^-]+){4}).*";
var output = Regex.Replace(text, pattern, "$1"); 
Console.WriteLine(output);  // abc-8479fe75-82rb5-45g00-b563

If we can rely on the input always having 6 hyphen separated components, we could also use this version:

var text = "abc-8479fe75-82rb5-45g00-b563-a7346703098b";
var pattern = @"-[^-]+$";
var output = Regex.Replace(text, pattern, ""); 
Console.WriteLine(output);  // abc-8479fe75-82rb5-45g00-b563

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);

I think this should be the most performant

public string GetSubString(string text)
{
    var count = 0;
    for (int i = text.Length-1; i > 0; i--)
    {
        if (text[i] == '-') count++;
        if (count == 5) return text.Substring(i);
    }
    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM