字符串有多少个参数 [英] String has how many parameters
问题描述
例如如果字符串是{0}是不一样的{1},我想知道这个字符串接受两个参数
例如。如果字符串是{0}与{1}和{2}不一样,则字符串接受3个参数
如何有效地找到它?
params对象[]
数组,可以处理任意大的值项目。 b 对于每个对象
值,都会调用 .ToString()
方法来解析格式模式
编辑:似乎我误解了您的问题。如果您想知道您的格式需要多少个参数,您可以使用正则表达式来发现:
字符串模式={0} {1:00} {{2}},失败:{0} {{{1}}},失败:{0}({0});
int count = Regex.Matches(Regex.Replace(pattern,
@(\ {{2} | \} {2}),),//移除转义大括号
@\ {\ d +(?: \:?[^}] *)\})。 //返回6
由于 Benjamin 在评论中指出,也许你需要知道不同的引用的数目。如果你不使用Linq,你可以这样:
pre $ int $ count = Regex.Matches(Regex.Replace(pattern,
@(\ {{2} | \} {2}),),//移除转义大括号
@\ {(\ d +)(?:\\ ()()匹配>();匹配>()
.SelectMany(match => match.Groups.OfType< Group> $ b .Select(index => Int32.Parse(index.Value))
.Max()+ 1; //返回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;
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 as {1}", I would like to know that this string accepts two parameters For eg. if the string was "{0} is not the same as {1} and {2}", the string accepts 3 parameters
How can I find this efficiently?
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<Match>()
.SelectMany(match => match.Groups.OfType<Group>().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<Match>()
.Select(match => int.Parse(match.Groups[1].Value))
.Union(Enumerable.Repeat(-1, 1))
.Max() + 1;
这篇关于字符串有多少个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!