Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse of String.Format? [duplicate]

Tags:

string

c#

.net

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.

like image 599
strager Avatar asked Oct 02 '09 20:10

strager


2 Answers

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

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

like image 151
BobbyShaftoe Avatar answered Oct 19 '22 05:10

BobbyShaftoe


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

like image 35
Joel Coehoorn Avatar answered Oct 19 '22 03:10

Joel Coehoorn