文字列を数値に変換する
幾つかの方法についてのサンプルです。
数値に変換できない文字列を与えると
FormatException例外が発生します。
C#
try
{
// 数値文字列を数値に
int a = int.Parse("10");
Console.WriteLine( "a = {0}", a );
// string型数値を数値に
string str = "20";
int b = int.Parse(str);
Console.WriteLine( "b = {0}", b );
// Convertで変換
int c = Convert.ToInt32("30");
Console.WriteLine( "c = {0}", c );
// 変換に失敗するケース
int d = Convert.ToInt32("( ゚∀゚)");
Console.WriteLine( "d = {0}", d );
}
catch( System.FormatException ex )
{
// 変換できない文字列を与えると例外が発生
Console.WriteLine( ex.Message );
}
VB.NET
Try
' 数値文字列を数値に
Dim a As Integer = Integer.Parse("10")
Console.WriteLine("a = {0}", a)
' string型数値を数値に
Dim str As String = "20"
Dim b As Integer = Integer.Parse(Str)
Console.WriteLine("b = {0}", b)
' Convertで変換
Dim c As Integer = Convert.ToInt32("30")
Console.WriteLine("c = {0}", c)
' 変換に失敗するケース
Dim d As Integer = Convert.ToInt32("( ゚∀゚)")
Console.WriteLine("d = {0}", d)
Catch ex As FormatException
' 変換できない文字列を与えると例外が発生
Console.WriteLine(ex.Message)
End Try
VC.NET
try
{
// 数値文字列を数値に
int a = Int32::Parse("10");
Console::WriteLine( S"a = {0}", __box(a) );
// string型数値を数値に
String *str = "20";
int b = Int32::Parse(str);
Console::WriteLine( S"b = {0}", __box(b) );
// Convertで変換
int c = Convert::ToInt32("30");
Console::WriteLine( S"c = {0}", __box(c) );
// 変換に失敗するケース
int d = Convert::ToInt32("( ゚∀゚)");
Console::WriteLine( S"d = {0}", __box(d) );
}
catch( System::FormatException *ex )
{
// 変換できない文字列を与えると例外が発生
Console::WriteLine( ex->Message );
}
【実行結果】
a = 10
b = 20
c = 30
入力文字列の形式が正しくありません。