如何將字串轉換成數位(C# 程式設計手冊)

您可以呼叫Parse在數值類型上找到的 或 TryParse 方法,doublelongint或使用 類別中的 System.Convert 方法,將轉換成string數位。

呼叫方法(例如)或 Parse 方法(例如,例如,var number = int.Parse("11"))會稍微更有效率且直接TryParseint.TryParse("11", out number) 使用 Convert 方法比實作 IConvertible 的一般物件更有用。

Parse您在預期字串包含的數值類型上使用 或 TryParse 方法,例如 System.Int32 類型。 Convert.ToInt32 方法會在內部使用 ParseParse方法會傳回已轉換的數位;TryParse方法會傳回布爾值,指出轉換是否成功,並在參數中out傳回轉換的數位。 如果字串不是有效的格式, Parse 則會擲回例外狀況,但 TryParse 會傳 false回 。 呼叫 Parse 方法時,您應該一律使用例外狀況處理,在剖析作業失敗時攔截 FormatException

呼叫 Parse 或 TryParse 方法

ParseTryParse 方法會忽略字串開頭和結尾的空格符,但所有其他字元都必須是構成適當數值類型的字元(int、、ulonglong、、floatdecimal等等)。 若構成數字的字串內有任何空格,則會造成錯誤。 例如,您可以使用 decimal.TryParse 來剖析 「10」、「10.3」 或 「10」,但您無法使用此方法剖析 「10X」、“1 0” (記下內嵌空間)、“10.3” (記下內嵌空間)、“10e1” (float.TryParse 在這裡運作)等等。 值為 或String.Empty無法成功剖析的null字串。 您可以透過呼叫 String.IsNullOrEmpty 方法,在嘗試剖析 Null 或空字串之前先進行檢查。

下列範例示範對 ParseTryParse 的成功呼叫與不成功的呼叫。

using System;

public static class StringConversion
{
    public static void Main()
    {
        string input = String.Empty;
        try
        {
            int result = Int32.Parse(input);
            Console.WriteLine(result);
        }
        catch (FormatException)
        {
            Console.WriteLine($"Unable to parse '{input}'");
        }
        // Output: Unable to parse ''

        try
        {
            int numVal = Int32.Parse("-105");
            Console.WriteLine(numVal);
        }
        catch (FormatException e)
        {
            Console.WriteLine(e.Message);
        }
        // Output: -105

        if (Int32.TryParse("-105", out int j))
        {
            Console.WriteLine(j);
        }
        else
        {
            Console.WriteLine("String could not be parsed.");
        }
        // Output: -105

        try
        {
            int m = Int32.Parse("abc");
        }
        catch (FormatException e)
        {
            Console.WriteLine(e.Message);
        }
        // Output: Input string was not in a correct format.

        const string inputString = "abc";
        if (Int32.TryParse(inputString, out int numValue))
        {
            Console.WriteLine(numValue);
        }
        else
        {
            Console.WriteLine($"Int32.TryParse could not parse '{inputString}' to an int.");
        }
        // Output: Int32.TryParse could not parse 'abc' to an int.
    }
}

下列範例說明剖析預期包含前置數值字元(包括十六進位字元)和尾端非數值字元的字串的方法。 在呼叫 TryParse 方法之前,它會將字串開頭的有效字元指派到新字串。 因為要剖析的字串包含幾個字元,因此範例會呼叫 String.Concat 方法,將有效的字元指派給新的字串。 針對較大的字串,可以改為使用 StringBuilder 類別。

using System;

public static class StringConversion
{
    public static void Main()
    {
        var str = "  10FFxxx";
        string numericString = string.Empty;
        foreach (var c in str)
        {
            // Check for numeric characters (hex in this case) or leading or trailing spaces.
            if ((c >= '0' && c <= '9') || (char.ToUpperInvariant(c) >= 'A' && char.ToUpperInvariant(c) <= 'F') || c == ' ')
            {
                numericString = string.Concat(numericString, c.ToString());
            }
            else
            {
                break;
            }
        }

        if (int.TryParse(numericString, System.Globalization.NumberStyles.HexNumber, null, out int i))
        {
            Console.WriteLine($"'{str}' --> '{numericString}' --> {i}");
        }
        // Output: '  10FFxxx' --> '  10FF' --> 4351

        str = "   -10FFXXX";
        numericString = "";
        foreach (char c in str)
        {
            // Check for numeric characters (0-9), a negative sign, or leading or trailing spaces.
            if ((c >= '0' && c <= '9') || c == ' ' || c == '-')
            {
                numericString = string.Concat(numericString, c);
            }
            else
            {
                break;
            }
        }

        if (int.TryParse(numericString, out int j))
        {
            Console.WriteLine($"'{str}' --> '{numericString}' --> {j}");
        }
        // Output: '   -10FFXXX' --> '   -10' --> -10
    }
}

呼叫 Convert 方法

下表列出您可以用來將字串轉換為數字的一些方法 (來自 Convert 類別)。

數值類型 方法
decimal ToDecimal(String)
float ToSingle(String)
double ToDouble(String)
short ToInt16(String)
int ToInt32(String)
long ToInt64(String)
ushort ToUInt16(String)
uint ToUInt32(String)
ulong ToUInt64(String)

下列範例會呼叫 Convert.ToInt32(String) 方法,將輸入字串 轉換成 int。此範例會擷取此方法擲回的兩個最常見例外狀況: FormatExceptionOverflowException。 若產生的數字可在不超過 Int32.MaxValue 的情況下遞增,範例會增加 1 到結果並顯示輸出。

using System;

public class ConvertStringExample1
{
    static void Main(string[] args)
    {
        int numVal = -1;
        bool repeat = true;

        while (repeat)
        {
            Console.Write("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive): ");

            string? input = Console.ReadLine();

            // ToInt32 can throw FormatException or OverflowException.
            try
            {
                numVal = Convert.ToInt32(input);
                if (numVal < Int32.MaxValue)
                {
                    Console.WriteLine("The new value is {0}", ++numVal);
                }
                else
                {
                    Console.WriteLine("numVal cannot be incremented beyond its current value");
                }
           }
            catch (FormatException)
            {
                Console.WriteLine("Input string is not a sequence of digits.");
            }
            catch (OverflowException)
            {
                Console.WriteLine("The number cannot fit in an Int32.");
            }

            Console.Write("Go again? Y/N: ");
            string? go = Console.ReadLine();
            if (go?.ToUpper() != "Y")
            {
                repeat = false;
            }
        }
    }
}
// Sample Output:
//   Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): 473
//   The new value is 474
//   Go again? Y/N: y
//   Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): 2147483647
//   numVal cannot be incremented beyond its current value
//   Go again? Y/N: y
//   Enter a number between -2,147,483,648 and +2,147,483,647 (inclusive): -1000
//   The new value is -999
//   Go again? Y/N: n