Analizzare una stringa in int/lungo usando stringhe di formato personalizzato
-
13-11-2019 - |
Domanda
In C#.NET, ecco un semplice esempio di come formattare i numeri in stringhe usando stringhe di formato personalizzato: (Esempio tratto da: http://www.csharp-examples.net/string-format-int/)
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"
C'è un modo per convertire questa stringa formattata in un lungo/numero intero? C'è in qualche modo per farlo:
long PhoneNumber = Int32.Parse("89-5871-2551", "{0:##-####-####}");
Ho visto che DateTime ha un metodo ParseExact che può fare bene questo. Ma non ho visto nulla del genere per int/lungo/decimale/doppio.
Soluzione
Basta rialdare tutti i caratteri non numerici, quindi analizzare quella stringa.
Altri suggerimenti
Puoi riassumere tutti i numeri non numerici e ciò che ti rimane è una stringa di numeri che puoi analizzare.
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.
}
Bene, puoi sempre fare
long PhoneNumber = Int32.Parse("89-5871-2551".
Replace(new char[]{'-','+',whatever..}).Trim());
A proposito, considerando che stai analizzando una corda ricevuta da alcuni IO
, Suggerirei di utilizzare più sicuro (in termini di conversione) Int32.tryparse metodo.
Come voi descritto non esiste in realtà.