HOW TO:將 string 轉換為 int (C# 程式設計手冊)

更新:2007 年 11 月

這些範例會示範許多不同的方法,讓您將 string 轉換為 int。舉例來說,從命令列引數取得數值輸入時,這種轉換就很有用。將字串轉換為其他數值型別還有一些類似的方法,例如 floatlong。下表會列出這些方法。

數字型別

方法

decimal

ToDecimal(String)

float

ToSingle(String)

double

ToDouble(String)

short

ToInt16(String)

long

ToInt64(String)

ushort

ToUInt16(String)

uint

ToUInt32(String)

ulong

ToUInt64(String)

範例

這個範例會呼叫 ToInt32(String) 方法,將字串 "29" 轉換為 int。接著會將 1 加入結果,並列印輸出。

int numVal = Convert.ToInt32("29");
numVal++;

Console.WriteLine(numVal);
// Output: 30

將 string 轉換為 int 的另一個方法是透過 System.Int32 結構 (Struct) 的 ParseTryParse 方法。ToUInt32 方法會在內部使用 Parse。如果字串的格式無效,Parse 會擲回例外狀況,而 TryParse 不會擲回例外狀況但傳回 false。下列範例會示範 ParseTryParse 成功與不成功的呼叫。

int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105
int j;
Int32.TryParse("-105", out j);
Console.WriteLine(j);
// Output: -105
try
{
    int m = Int32.Parse("abc");
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.
string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);

if (!parsed)
    Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);

// Output: Int32.TryParse could not parse 'abc' to an int.

請參閱

工作

HOW TO:判斷字串是否表示數值 (C# 程式設計手冊)

參考

資料型別 (C# 程式設計手冊)