开发者

c# Use String format to read a string into an object

I've created a string using开发者_如何学C

String.Format(IPAddressRangeFormat, StartIP, EndIP);

Now I need to read the string back into the StartIP and EndIP objects.

What's the easiest way to do so in c#?

THanks, Li.


There is no easy way to do this as the reverse of a String.Format is not deterministic.

Both :

String.Format( "{0}{1}", "123", "456" )
String.Format( "{0}{1}", "12", "3456" )

gives you 123456. The machine won't just guess which one you want.

However there is a trickier way to do it, you do have regular expressions.

If you have :

String.Format ( "{0}-{1}",  StartIP, EndIP);

You could use an expression :

var matches = Regex.Match ( String.Format ( "{0}-{1}",  "127.0.0.1", "192.168.0.1"), "(?<startIP>.*)-(?<endIP>.*)" );
Console.WriteLine ( matches.Groups["startIP"].Value ); // 127.0.0.1
Console.WriteLine ( matches.Groups["endIP"].Value );   // 192.168.0.1


Probably the best way to have the separate type like IPRange where you will have 2 IP's in costructor and overriden ToString(). Th parse back you probably will need to implement custom logic in lets say static Parse(string) member.


The thing you want to do called Parsing and it can't be performed by String.Format method.


Depending on your formatting for IPAddressRangeFormat, use ToString() ...then string.Split(':') ...replacing the ':' with whatever char you are using.

I would really need to see your format for IPAddressRangeFormat to provide a better answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜