String有多少个参数

Pra*_*ari 9 c# string format parameters

在使用String.Format格式化C#中的字符串之前,我想知道该字符串接受了多少个参数?

例如.如果字符串是"{0}与{1}不同",我想知道这个字符串接受两个参数,例如.如果字符串是"{0}与{1}和{2}不同",则该字符串接受3个参数

我怎样才能有效地找到它?

Rub*_*ias 7

String.Format接收带有formatvalue 的字符串参数和一个params object[]可以处理任意大值项的数组.

对于每个object值,.ToString()将调用它的方法来解析该格式模式

编辑:似乎我误解了你的问题.如果您想知道格式需要多少个参数,可以通过使用正则表达式来发现:

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
Run Code Online (Sandbox Code Playgroud)

正如本杰明在评论中指出的那样,也许你需要知道不同参考文献的数量.如果您不使用Linq,请转到:

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

这也解决了@ 280Z28发现的最后一个问题.

由280Z28编辑:这不会验证输入,但对于任何有效输入将给出正确的答案:

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