Parsing a string in int / long using custom format strings

In C # .Net, here is a simple example of how to format numbers into strings using custom format strings: (example taken from: http://www.csharp-examples.net/string-format-int/ )

String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456" String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551" 

Is there a way to convert this formatted string back to long / integer? Is there any way to do this:

 long PhoneNumber = Int32.Parse("89-5871-2551", "{0:##-####-####}"); 

I saw that DateTime has a ParseExact method that can work well. But I have not seen such a thing for int / long / decimal / double.

+4
source share
3 answers

Just cut out all the non-numeric characters, then parse this string.

0
source

You can repeatedly print all non-numeric numbers, but what you left is a string of numbers that you can parse.

 var myPhoneNumber = "89-5871-2551"; var strippedPhoneNumber = Regex.Replace(myPhoneNumber, @"[^\d]", ""); int intRepresentation; if (Int32.TryParse(strippedPhoneNumber, out intRepresentation)) { // It was assigned, intRepresentation = 8958712551 // now you can use intRepresentation. } else { // It was not assigned, intRepresentation is still null. } 
+3
source

Well, you can always do

 long PhoneNumber = Int32.Parse("89-5871-2551". Replace(new char[]{'-','+',whatever..}).Trim()); 

By the way, given that you are parsing the string received from some IO , I would suggest using the more secure (from the point of view of conversion) Int32.TryParse .

This way, like you , doesn’t really exist.

+1
source

Source: https://habr.com/ru/post/1398676/


All Articles