文字列を数値に変換する方法 (C# プログラミング ガイド)
string
を数値に変換するには、数値型 (int
、long
、double
など) で見つかる Parse
または TryParse
メソッドを呼び出すか、System.Convert クラスのメソッドを使用します。
TryParse
メソッド (たとえば int.TryParse("11", out number)
) または Parse
メソッド (たとえば var number = int.Parse("11")
) を呼び出す方がいくらか効率的で簡単です。 IConvertible を実装している一般的なオブジェクトでは、Convert メソッドを使用するのがより便利です。
文字列に含まれていると思われる数値型 (System.Int32 型など) の Parse
または TryParse
メソッドを使用します。 Convert.ToInt32 メソッドは、Parse を内部的に使用します。 Parse
メソッドからは、変換された数値が返されます。TryParse
メソッドからは変換が成功したかどうかを示すブール値が返され、変換された数値は out
パラメーターで戻されます。 文字列の形式が無効である場合、Parse
では例外がスローされますが、TryParse
では false
が返されます。 Parse
メソッドを呼び出すときは常に例外処理を使用し、解析操作が失敗したときの FormatException をキャッチする必要があります。
Parse または TryParse メソッドを呼び出す
文字列の先頭と末尾の空白文字は、Parse
および TryParse
メソッドによって無視されますが、その他のすべての文字は、適切な数値型 (int
、long
、ulong
、float
、decimal
など) を形成する文字である必要があります。 数値を形成する文字列内に空白文字があると、エラーになります。 たとえば、"10"、"10.3"、または " 10 " を解析するために decimal.TryParse
を使用することはできますが、"10X"、"1 0" (埋め込まれたスペースに注意)、"10 .3" (埋め込まれたスペースに注意)、"10e1" (この場合は float.TryParse
を使用) などからこのメソッドを使用して 10 を解析することはできません。 値が null
または String.Empty の文字列は正常に解析できません。 String.IsNullOrEmpty メソッドを呼び出すことで、解析を試みる前に null または空の文字列を確認できます。
次の例は、Parse
および TryParse
の呼び出しの成功例と失敗例の両方を示しています。
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.
}
}
次の例は、先頭に数字 (16 進数文字を含む)、末尾に数字以外の文字を含むと予想される文字列を解析する 1 つのアプローチを示しています。 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 に変換します。例では、このメソッドによってスローされる 2 つの最も一般的な例外である FormatException と OverflowException をキャッチします。 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
.NET