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

Time:09-22

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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;
}
  • Related