在C#中使用String.Format格式化一个字符串之前,我想知道这个字符串接受多少个参数?
例如。如果字符串是“{0} is not the same as {1}”,我想知道这个字符串接受两个参数 例如。如果字符串是“{0} 与 {1} 和 {2} 不同”,则该字符串接受 3 个参数
我怎样才能有效地找到它?
最佳答案
String.Format
接收一个带有 format
值的字符串参数,以及一个 params object[]
数组,它可以处理任意大的有值(value)的元素。
对于每个 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
作为Benjamin在评论中指出,也许您确实需要知道不同 引用的数量。如果您不使用 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
这也是地址@ 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;
关于c# - 字符串有多少个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2156497/