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.Formatreceives a string argument withformatvalue, and anparams object[]array, which can deal with an arbitrary large value items.For every
objectvalue, it’s.ToString()method will be called to resolve that format patternEDIT: 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:
As Benjamin noted in comments, maybe you do need to know number of different references. If you don’t using Linq, here you go:
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: