Analysieren numerischer Zeichenfolgen in .NETParsing Numeric Strings in NET
Alle numerischen Typen weisen zwei statische Analysemethoden auf, Parse
und TryParse
, mit denen Sie die Zeichenfolgendarstellung einer Zahl in einen numerischen Typ konvertieren können.All numeric types have two static parsing methods, Parse
and TryParse
, that you can use to convert the string representation of a number into a numeric type. Mit diesen Methoden können Sie Zeichenfolgen analysieren, die mithilfe der Formatzeichenfolgen erstellt wurden, die unter Standardformatzeichenfolgen für Zahlen und Benutzerdefinierte Zahlenformatzeichenfolgen dokumentiert sind.These methods enable you to parse strings that were produced by using the format strings documented in Standard Numeric Format Strings and Custom Numeric Format Strings. In der Standardeinstellung können die Methoden Parse
und TryParse
Zeichenfolgen, die nur Vorkommastellen enthalten, erfolgreich in ganzzahlige Werte konvertieren.By default, the Parse
and TryParse
methods can successfully convert strings that contain integral decimal digits only to integer values. Sie können Zeichenfolgen, die Vor- und Nachkommastellen, Gruppentrennzeichen und ein Dezimaltrennzeichen enthalten, erfolgreich in Gleitkommawerte konvertieren.They can successfully convert strings that contain integral and fractional decimal digits, group separators, and a decimal separator to floating-point values. Die Parse
-Methode löst eine Ausnahme aus, wenn der Vorgang einen Fehler verursacht, wohingegen die TryParse
-Methode false
zurückgibt.The Parse
method throws an exception if the operation fails, whereas the TryParse
method returns false
.
Analyse und FormatanbieterParsing and Format Providers
In der Regel unterscheiden sich die Zeichenfolgendarstellungen numerischer Werte je nach Kultur.Typically, the string representations of numeric values differ by culture. Elemente numerischer Zeichenfolgen wie Währungssymbole, Gruppentrennzeichen (oder Tausendertrennzeichen) und Dezimaltrennzeichen variieren alle je nach Kultur.Elements of numeric strings such as currency symbols, group (or thousands) separators, and decimal separators all vary by culture. Analysemethoden verwenden entweder implizit oder explizit einen Formatanbieter, der diese kulturspezifischen Variationen erkennt.Parsing methods either implicitly or explicitly use a format provider that recognizes these culture-specific variations. Wird in einem Aufruf der Parse
- oder der TryParse
-Methode kein Formatanbieter angegeben, so wird der der aktuellen Threadkultur zugeordnete Formatanbieter verwendet (das von der NumberFormatInfo.CurrentInfo-Eigenschaft zurückgegebene NumberFormatInfo-Objekt).If no format provider is specified in a call to the Parse
or TryParse
method, the format provider associated with the current thread culture (the NumberFormatInfo object returned by the NumberFormatInfo.CurrentInfo property) is used.
Ein Formatanbieter wird durch eine IFormatProvider-Implementierung dargestellt.A format provider is represented by an IFormatProvider implementation. Diese Schnittstelle verfügt über einen einzelnen Member, die GetFormat-Methode, deren einziger Parameter ein Type-Objekt für den zu formatierenden Typ ist.This interface has a single member, the GetFormat method, whose single parameter is a Type object that represents the type to be formatted. Diese Methode gibt das Objekt mit den Formatierungsinformationen zurück.This method returns the object that provides formatting information. .NET unterstützt die folgenden beiden IFormatProvider-Implementierungen zur Analyse numerischer Zeichenfolgen:.NET supports the following two IFormatProvider implementations for parsing numeric strings:
Ein CultureInfo-Objekt, dessen CultureInfo.GetFormat-Methode ein NumberFormatInfo-Objekt mit kulturspezifischen Formatierungsinformationen zurückgibt.A CultureInfo object whose CultureInfo.GetFormat method returns a NumberFormatInfo object that provides culture-specific formatting information.
Ein NumberFormatInfo Objekt, dessen NumberFormatInfo.GetFormat-Methode sich selbst zurückgibt.A NumberFormatInfo object whose NumberFormatInfo.GetFormat method returns itself.
Im folgenden Beispiel wird versucht, jede Zeichenfolge in einem Array in einen Double-Wert zu konvertieren.The following example tries to convert each string in an array to a Double value. Zuerst wird versucht, die Zeichenfolge anhand eines Formatanbieters zu analysieren, der die Konventionen der Kultur „Englisch (USA)“ wiedergibt.It first tries to parse the string by using a format provider that reflects the conventions of the English (United States) culture. Wenn dieser Vorgang eine FormatException auslöst, wird versucht, die Zeichenfolge anhand eines Formatanbieters zu analysieren, der die Konventionen der Kultur „Französisch (Frankreich)“ darstellt.If this operation throws a FormatException, it tries to parse the string by using a format provider that reflects the conventions of the French (France) culture.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] values = { "1,304.16", "$1,456.78", "1,094", "152",
"123,45 €", "1 304,16", "Ae9f" };
double number;
CultureInfo culture = null;
foreach (string value in values) {
try {
culture = CultureInfo.CreateSpecificCulture("en-US");
number = Double.Parse(value, culture);
Console.WriteLine("{0}: {1} --> {2}", culture.Name, value, number);
}
catch (FormatException) {
Console.WriteLine("{0}: Unable to parse '{1}'.",
culture.Name, value);
culture = CultureInfo.CreateSpecificCulture("fr-FR");
try {
number = Double.Parse(value, culture);
Console.WriteLine("{0}: {1} --> {2}", culture.Name, value, number);
}
catch (FormatException) {
Console.WriteLine("{0}: Unable to parse '{1}'.",
culture.Name, value);
}
}
Console.WriteLine();
}
}
}
// The example displays the following output:
// en-US: 1,304.16 --> 1304.16
//
// en-US: Unable to parse '$1,456.78'.
// fr-FR: Unable to parse '$1,456.78'.
//
// en-US: 1,094 --> 1094
//
// en-US: 152 --> 152
//
// en-US: Unable to parse '123,45 €'.
// fr-FR: Unable to parse '123,45 €'.
//
// en-US: Unable to parse '1 304,16'.
// fr-FR: 1 304,16 --> 1304.16
//
// en-US: Unable to parse 'Ae9f'.
// fr-FR: Unable to parse 'Ae9f'.
Imports System.Globalization
Module Example
Public Sub Main()
Dim values() As String = {"1,304.16", "$1,456.78", "1,094", "152",
"123,45 €", "1 304,16", "Ae9f"}
Dim number As Double
Dim culture As CultureInfo = Nothing
For Each value As String In values
Try
culture = CultureInfo.CreateSpecificCulture("en-US")
number = Double.Parse(value, culture)
Console.WriteLine("{0}: {1} --> {2}", culture.Name, value, number)
Catch e As FormatException
Console.WriteLine("{0}: Unable to parse '{1}'.",
culture.Name, value)
culture = CultureInfo.CreateSpecificCulture("fr-FR")
Try
number = Double.Parse(value, culture)
Console.WriteLine("{0}: {1} --> {2}", culture.Name, value, number)
Catch ex As FormatException
Console.WriteLine("{0}: Unable to parse '{1}'.",
culture.Name, value)
End Try
End Try
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' en-US: 1,304.16 --> 1304.16
'
' en-US: Unable to parse '$1,456.78'.
' fr-FR: Unable to parse '$1,456.78'.
'
' en-US: 1,094 --> 1094
'
' en-US: 152 --> 152
'
' en-US: Unable to parse '123,45 €'.
' fr-FR: Unable to parse '123,45 €'.
'
' en-US: Unable to parse '1 304,16'.
' fr-FR: 1 304,16 --> 1304.16
'
' en-US: Unable to parse 'Ae9f'.
' fr-FR: Unable to parse 'Ae9f'.
Analyse und NumberStyles-WerteParsing and NumberStyles Values
Die Stilelemente (z.B. Leerzeichen, Gruppentrennzeichen und Dezimaltrennzeichen), die der Analysevorgang verarbeiten kann, werden durch einen NumberStyles-Enumerationswert definiert.The style elements (such as white space, group separators, and decimal separator) that the parse operation can handle are defined by a NumberStyles enumeration value. Standardmäßig werden Zeichenfolgen, die ganzzahlige Werte darstellen, über den NumberStyles.Integer-Wert analysiert, der nur Ziffern, vorangestellte und nachfolgende Leerzeichen sowie ein Vorzeichen zulässt.By default, strings that represent integer values are parsed by using the NumberStyles.Integer value, which permits only numeric digits, leading and trailing white space, and a leading sign. Zeichenfolgen, die Gleitkommawerte darstellen, werden mithilfe einer Kombination der Werte NumberStyles.Float und NumberStyles.AllowThousands analysiert. Dieser zusammengesetzte Stil lässt Dezimalstellen sowie vorangestellte und nachfolgende Leerzeichen, ein Vorzeichen, ein Dezimaltrennzeichen, ein Gruppentrennzeichen und einen Exponenten zu.Strings that represent floating-point values are parsed using a combination of the NumberStyles.Float and NumberStyles.AllowThousands values; this composite style permits decimal digits along with leading and trailing white space, a leading sign, a decimal separator, a group separator, and an exponent. Durch den Aufruf einer Überladung der Parse
- oder der TryParse
-Methode mit einem Parameter vom Typ NumberStyles und durch Festlegen von NumberStyles-Flags können Sie die Stilelemente steuern, die in der Zeichenfolge vorhanden sein dürfen, damit der Analysevorgang erfolgreich durchgeführt werden kann.By calling an overload of the Parse
or TryParse
method that includes a parameter of type NumberStyles and setting one or more NumberStyles flags, you can control the style elements that can be present in the string for the parse operation to succeed.
Beispielsweise kann eine Zeichenfolge, die ein Gruppentrennzeichen enthält, nicht mithilfe der Int32.Parse(String)-Methode in einen Int32-Wert konvertiert werden.For example, a string that contains a group separator cannot be converted to an Int32 value by using the Int32.Parse(String) method. Die Konvertierung ist jedoch erfolgreich, wenn Sie das NumberStyles.AllowThousands-Flag verwenden, wie im folgenden Beispiel veranschaulicht.However, the conversion succeeds if you use the NumberStyles.AllowThousands flag, as the following example illustrates.
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string value = "1,304";
int number;
IFormatProvider provider = CultureInfo.CreateSpecificCulture("en-US");
if (Int32.TryParse(value, out number))
Console.WriteLine("{0} --> {1}", value, number);
else
Console.WriteLine("Unable to convert '{0}'", value);
if (Int32.TryParse(value, NumberStyles.Integer | NumberStyles.AllowThousands,
provider, out number))
Console.WriteLine("{0} --> {1}", value, number);
else
Console.WriteLine("Unable to convert '{0}'", value);
}
}
// The example displays the following output:
// Unable to convert '1,304'
// 1,304 --> 1304
Imports System.Globalization
Module Example
Public Sub Main()
Dim value As String = "1,304"
Dim number As Integer
Dim provider As IFormatProvider = CultureInfo.CreateSpecificCulture("en-US")
If Int32.TryParse(value, number) Then
Console.WriteLine("{0} --> {1}", value, number)
Else
Console.WriteLine("Unable to convert '{0}'", value)
End If
If Int32.TryParse(value, NumberStyles.Integer Or NumberStyles.AllowThousands,
provider, number) Then
Console.WriteLine("{0} --> {1}", value, number)
Else
Console.WriteLine("Unable to convert '{0}'", value)
End If
End Sub
End Module
' The example displays the following output:
' Unable to convert '1,304'
' 1,304 --> 1304
Warnung
Beim Analysevorgang werden immer die Formatierungskonventionen einer bestimmten Kultur verwendet.The parse operation always uses the formatting conventions of a particular culture. Wenn Sie keine Kultur durch Übergabe eines CultureInfo- oder NumberFormatInfo-Objekts angeben, wird die dem aktuellen Thread zugeordnete Kultur verwendet.If you do not specify a culture by passing a CultureInfo or NumberFormatInfo object, the culture associated with the current thread is used.
Die folgende Tabelle enthält die Member der NumberStyles-Enumeration und beschreibt, wie sich diese auf den Analysevorgang auswirken.The following table lists the members of the NumberStyles enumeration and describes the effect that they have on the parsing operation.
NumberStyles-WertNumberStyles value | Auswirkung auf die zu analysierende ZeichenfolgeEffect on the string to be parsed |
---|---|
NumberStyles.None | Nur Ziffern sind zulässig.Only numeric digits are permitted. |
NumberStyles.AllowDecimalPoint | Das Dezimaltrennzeichen und Nachkommastellen sind zulässig.The decimal separator and fractional digits are permitted. Für ganzzahlige Werte ist nur 0 (null) als Nachkommastelle zulässig.For integer values, only zero is permitted as a fractional digit. Gültige Dezimaltrennzeichen werden mithilfe der NumberFormatInfo.NumberDecimalSeparator- oder NumberFormatInfo.CurrencyDecimalSeparator-Eigenschaft ermittelt.Valid decimal separators are determined by the NumberFormatInfo.NumberDecimalSeparator or NumberFormatInfo.CurrencyDecimalSeparator property. |
NumberStyles.AllowExponent | Das Zeichen „e“ oder „E“ kann zum Angeben der Exponentialschreibweise verwendet werden.The "e" or "E" character can be used to indicate exponential notation. Weitere Informationen finden Sie unter NumberStyles.See NumberStyles for additional information. |
NumberStyles.AllowLeadingWhite | Vorangestellte Leerzeichen sind zulässig.Leading white space is permitted. |
NumberStyles.AllowTrailingWhite | Nachfolgende Leerzeichen sind zulässig.Trailing white space is permitted. |
NumberStyles.AllowLeadingSign | Ein positives oder negatives Vorzeichen kann numerischen Zeichen vorangestellt werden.A positive or negative sign can precede numeric digits. |
NumberStyles.AllowTrailingSign | Ein positives oder negatives Vorzeichen kann numerischen Zeichen nachfolgen.A positive or negative sign can follow numeric digits. |
NumberStyles.AllowParentheses | Klammern können zum Festlegen negativer Werte verwendet werden.Parentheses can be used to indicate negative values. |
NumberStyles.AllowThousands | Das Gruppentrennzeichen ist zulässig.The group separator is permitted. Das Gruppentrennzeichen wird mithilfe der NumberFormatInfo.NumberGroupSeparator- oder NumberFormatInfo.CurrencyGroupSeparator-Eigenschaft ermittelt.The group separator character is determined by the NumberFormatInfo.NumberGroupSeparator or NumberFormatInfo.CurrencyGroupSeparator property. |
NumberStyles.AllowCurrencySymbol | Das Währungssymbol ist zulässig.The currency symbol is permitted. Das Währungssymbol wird mit der NumberFormatInfo.CurrencySymbol-Eigenschaft definiert.The currency symbol is defined by the NumberFormatInfo.CurrencySymbol property. |
NumberStyles.AllowHexSpecifier | Die zu analysierende Zeichenfolge wird als Hexadezimalzahl interpretiert.The string to be parsed is interpreted as a hexadecimal number. Sie kann die Hexadezimalzeichen 0 bis 9, A bis F und a bis f enthalten.It can include the hexadecimal digits 0-9, A-F, and a-f. Dieses Flag kann nur für die Analyse ganzzahliger Werte verwendet werden.This flag can be used only to parse integer values. |
Darüber hinaus stellt die NumberStyles-Enumeration die folgenden zusammengesetzten Stile bereit, die mehrere NumberStyles-Flags umfassen.In addition, the NumberStyles enumeration provides the following composite styles, which include multiple NumberStyles flags.
Analyse und Unicode-ZiffernParsing and Unicode Digits
Der Unicode-Standard definiert Codepunkte für Ziffern in verschiedenen Schreibsystemen.The Unicode standard defines code points for digits in various writing systems. Beispielsweise stehen Codepunkte von U+0030 bis U+0039 für die grundlegenden lateinischen Ziffern 0 bis 9, Codepunkte von U+09E6 bis U+09EF für die Bangla-Ziffern 0 bis 9 und Codepunkte von U+FF10 bis U+FF19 für Ziffern voller Breite von 0 bis 9.For example, code points from U+0030 to U+0039 represent the basic Latin digits 0 through 9, code points from U+09E6 to U+09EF represent the Bangla digits 0 through 9, and code points from U+FF10 to U+FF19 represent the Fullwidth digits 0 through 9. Allerdings werden von den Analysemethoden nur die grundlegenden lateinischen Ziffern von 0 bis 9 mit den Codepunkten von U+0030 bis U+0039 erkannt.However, the only numeric digits recognized by parsing methods are the basic Latin digits 0-9 with code points from U+0030 to U+0039. Wenn einer numerischen Analysemethode eine Zeichenfolge übergeben wird, die andere Ziffern enthält, löst die Methode eine FormatException aus.If a numeric parsing method is passed a string that contains any other digits, the method throws a FormatException.
Im folgenden Beispiel wird die Int32.Parse-Methode zum Analysieren von Zeichenfolgen verwendet, die aus Ziffern unterschiedlicher Schreibsysteme bestehen.The following example uses the Int32.Parse method to parse strings that consist of digits in different writing systems. Wie die Ausgabe des Beispiels zeigt, verläuft die Analyse der grundlegenden lateinischen Ziffern erfolgreich, aber der Versuch zum Analysieren der vollbreiten, der arabisch-indischen und der Bangla-Ziffern verursacht einen Fehler.As the output from the example shows, the attempt to parse the basic Latin digits succeeds, but the attempt to parse the Fullwidth, Arabic-Indic, and Bangla digits fails.
using System;
public class Example
{
public static void Main()
{
string value;
// Define a string of basic Latin digits 1-5.
value = "\u0031\u0032\u0033\u0034\u0035";
ParseDigits(value);
// Define a string of Fullwidth digits 1-5.
value = "\uFF11\uFF12\uFF13\uFF14\uFF15";
ParseDigits(value);
// Define a string of Arabic-Indic digits 1-5.
value = "\u0661\u0662\u0663\u0664\u0665";
ParseDigits(value);
// Define a string of Bangla digits 1-5.
value = "\u09e7\u09e8\u09e9\u09ea\u09eb";
ParseDigits(value);
}
static void ParseDigits(string value)
{
try {
int number = Int32.Parse(value);
Console.WriteLine("'{0}' --> {1}", value, number);
}
catch (FormatException) {
Console.WriteLine("Unable to parse '{0}'.", value);
}
}
}
// The example displays the following output:
// '12345' --> 12345
// Unable to parse '12345'.
// Unable to parse '١٢٣٤٥'.
// Unable to parse '১২৩৪৫'.
Module Example
Public Sub Main()
Dim value As String
' Define a string of basic Latin digits 1-5.
value = ChrW(&h31) + ChrW(&h32) + ChrW(&h33) + ChrW(&h34) + ChrW(&h35)
ParseDigits(value)
' Define a string of Fullwidth digits 1-5.
value = ChrW(&hff11) + ChrW(&hff12) + ChrW(&hff13) + ChrW(&hff14) + ChrW(&hff15)
ParseDigits(value)
' Define a string of Arabic-Indic digits 1-5.
value = ChrW(&h661) + ChrW(&h662) + ChrW(&h663) + ChrW(&h664) + ChrW(&h665)
ParseDigits(value)
' Define a string of Bangla digits 1-5.
value = ChrW(&h09e7) + ChrW(&h09e8) + ChrW(&h09e9) + ChrW(&h09ea) + ChrW(&h09eb)
ParseDigits(value)
End Sub
Sub ParseDigits(value As String)
Try
Dim number As Integer = Int32.Parse(value)
Console.WriteLine("'{0}' --> {1}", value, number)
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'.", value)
End Try
End Sub
End Module
' The example displays the following output:
' '12345' --> 12345
' Unable to parse '12345'.
' Unable to parse '١٢٣٤٥'.
' Unable to parse '১২৩৪৫'.