Share via


方法: string を int に変換する (C# プログラミング ガイド)

以下の例では、stringint に変換するためのいくつかの方法を示します。 このような変換は、コマンド ライン引数から数値入力を取得するような場合などに便利です。 string を、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) メソッドを呼び出して、入力の stringint に変換します。 このメソッドからスローされる最も一般的な 2 種類の例外を、プログラムでキャッチします。 整数の格納場所がオーバーフローすることなく数字をインクリメントできる場合、プログラムは結果に 1 を加算し、出力を印刷します。

int numVal = -1;
bool repeat = true;

while (repeat == true)
{
    Console.WriteLine("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);
    }
    catch (FormatException e)
    {
        Console.WriteLine("Input string is not a sequence of digits.");
    }
    catch (OverflowException e)
    {
        Console.WriteLine("The number cannot fit in an Int32.");
    }
    finally
    {
        if (numVal < Int32.MaxValue)
        {
            Console.WriteLine("The new value is {0}", numVal + 1);
        }
        else
        {
            Console.WriteLine("numVal cannot be incremented beyond its current value");
        }
    }
    Console.WriteLine("Go again? Y/N");
    string go = Console.ReadLine();
    if (go == "Y" || go == "y")
    {
        repeat = true;
    }
    else
    {
        repeat = false;
    }
}
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();    

string から int への変換は、System.Int32 構造体の Parse メソッドまたは TryParse メソッドによっても実行できます。 ToUInt32 メソッドは、Parse を内部的に使用します。 string の形式が無効である場合、Parse が例外をスローするのに対し、TryParse は例外をスローする代わりに false を返します。 以下は、Parse および TryParse の呼び出しの成功例と失敗例の両方を示しています。

int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105
// TryParse returns true if the conversion succeeded
// and stores the result in the specified variable.
int j;
bool result = Int32.TryParse("-105", out j);
if (true == result)
    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.
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.

参照

処理手順

方法 : 文字列が数値を表しているかどうかを確認する (C# プログラミング ガイド)

参照

型 (C# プログラミング ガイド)