tags:

views:

280

answers:

3

Possible Duplicate:
Parsing formatted string.

How can I use a String.Format format and transform its output to its inputs?

For example:

string formatString = "My name is {0}.  I have {1} cow(s).";

string s = String.Format(formatString, "strager", 2);

// Call the magic method...
ICollection<string> parts = String.ReverseFormat(formatString, s);
// parts now contains "strager" and "2".

I know I can use regular expressions to do this, but I would like to use the same format string so I only need to maintain one line of code instead of two.

A: 

I don't believe there's anything in-box to support this, but in C#, you can pass an array of objects directly to any method taking params-marked array parameters, such as String.Format(). Other than that, I don't believe there's some way for C# & the .NET Framework to know that string X was built from magic format string Y and undo the merge.

Therefore, the only thing I can think of is that you could format your code thusly:

object[] parts = {"strager", 2};
string s = String.Format(formatString, parts);

// Later on use parts, converting each member .ToString()
foreach (object p in parts)
{
    Console.WriteLine(p.ToString());
}

Not ideal, and probably not quite what you're looking for, but I think it's the only way.

John Rudy
A: 

You'll have to implement it yourself, as there's nothing built in to do it for you.

To that end, I suggest you get the actual source code for the .Net string.format implmentation (actually, the relevant code is in StringBuilder.AppendFormat()). It's freely available, and it uses a state machine to walk the string in a very performant manner. You can mimic that code to also walk your formatted string and extract that data.

Note that it won't always be possible to go backwards. Sometimes the formatted string can have characters the match the format specifiers, making it difficult to impossible for the program to know what the original looked like. As I think about it, you might have better luck walking the original string to turn it into a regular expression, and then use that to do the match.

I'd also recommend renaming your method to InvertFormat(), because ReverseFormat sounds like you'd expect this output:

.)s(woc 2 evah .regarts si eman yM

Joel Coehoorn
That implementation is "free beer" free or "if you ever try to use this in actual code I'll sue your ass out of this planet for free" free?
Vinko Vrsalovic
free beer, but since you'd modify it it considerably to build something new, you should be safe.
Joel Coehoorn
A: 

Here is some code from someone attempting a Scanf equivalent in C#:

http://www.codeproject.com/KB/recipes/csscanf.aspx

BobbyShaftoe