String has how many parameters

前端 未结 3 2387
既然无缘
既然无缘 2021-02-20 15:39

Before using String.Format to format a string in C#, I would like to know how many parameters does that string accept?

For eg. if the string was \"{0} is not the same

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-20 16:43

    String.Format receives a string argument with format value, and an params object[] array, which can deal with an arbitrary large value items.

    For every object value, it's .ToString() method will be called to resolve that format pattern

    EDIT: Seems I misread your question. If you want to know how many arguments are required to your format, you can discover that by using a regular expression:

    string pattern = "{0} {1:00} {{2}}, Failure: {0}{{{1}}}, Failure: {0} ({0})";
    int count = Regex.Matches(Regex.Replace(pattern, 
        @"(\{{2}|\}{2})", ""), // removes escaped curly brackets
        @"\{\d+(?:\:?[^}]*)\}").Count; // returns 6
    

    As Benjamin noted in comments, maybe you do need to know number of different references. If you don't using Linq, here you go:

    int count = Regex.Matches(Regex.Replace(pattern, 
        @"(\{{2}|\}{2})", ""), // removes escaped curly brackets
        @"\{(\d+)(?:\:?[^}]*)\}").OfType()
        .SelectMany(match => match.Groups.OfType().Skip(1))
        .Select(index => Int32.Parse(index.Value))
        .Max() + 1; // returns 2
    

    This also address @280Z28 last problem spotted.

    Edit by 280Z28: This will not validate the input, but for any valid input will give the correct answer:

    int count2 =
        Regex.Matches(
            pattern.Replace("{{", string.Empty),
            @"\{(\d+)")
        .OfType()
        .Select(match => int.Parse(match.Groups[1].Value))
        .Union(Enumerable.Repeat(-1, 1))
        .Max() + 1;
    

提交回复
热议问题