文字列がC#の数値であるかどうかを確認します
この記事では、文字列がC#の数値であるかどうかを確認するためのさまざまな手法について説明します。
1.使用する TryParse()
方法
あなたは使用することができます TryParse()
文字列が数値であるかどうかを識別するメソッド。指定された文字列を同等の符号付き整数表現に変換することで機能し、 true
変換が成功した場合。それ以外は、 false
。コードは次のようになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { string s = "123"; int n; bool isNumeric = int.TryParse(s, out n); Console.WriteLine(n); // 123 Console.WriteLine(isNumeric); // True } } |
に注意してください TryParse()
メソッドは、変換が成功した場合に整数値を格納するOutパラメーターを取ります。 Outパラメータが不要な場合は、これを以下に短縮できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = "123"; bool isNumeric = int.TryParse(s, out _); Console.WriteLine(isNumeric); // True } } |
Outパラメータは、個別のステートメントで宣言および初期化されることに注意してください。 C# 7から、Outパラメーターをインラインで宣言して初期化できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string s = "123"; bool isNumeric = int.TryParse(s, out int n); Console.WriteLine(n); // 123 Console.WriteLine(isNumeric); // True } } |
2.使用する Char.IsDigit()
方法
The Char.IsDigit()
メソッドは、指定された文字が数字であるかどうかを示すブール値を返します。次のコード例は、 Char.IsDigit()
との方法 Enumerable.All()
文字列が数値であるかどうかを判断するメソッド。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; public class Example { public static void Main() { string s = "123"; bool isNumeric = s.All(char.IsDigit); Console.WriteLine(isNumeric); // True } } |
3.使用する Regex.IsMatch()
方法
最後に、正規表現を使用して、文字列が数値であるかどうかを確認できます。これは、 Regex.IsMatch()
指定された文字列が指定された正規表現と一致するかどうかを判別するメソッド。これを以下に示します。ご了承ください ^
文字列の先頭と一致し、 $
その終わりと一致します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string s = "123"; bool isNumeric = Regex.IsMatch(s, @"^\d+$"); Console.WriteLine(isNumeric); // True } } |
これで、文字列がC#の数値であるかどうかを確認できます。
こちらも参照: