如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
如果我有这些字符串:
"abc" =假 "123" =真 "ab2" = false
是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否是有效的数字?
当前回答
以防你不想用int。解析或双重。解析,你可以用这样的东西来滚动你自己的:
public static class Extensions
{
public static bool IsNumeric(this string s)
{
foreach (char c in s)
{
if (!char.IsDigit(c) && c != '.')
{
return false;
}
}
return true;
}
}
其他回答
int n;
bool isNumeric = int.TryParse("123", out n);
从c# 7开始更新:
var isNumeric = int.TryParse("123", out int n);
或者,如果不需要这个数字,可以丢弃out参数
var isNumeric = int.TryParse("123", out _);
变量可以被它们各自的类型替换!
//To my knowledge I did this in a simple way
static void Main(string[] args)
{
string a, b;
int f1, f2, x, y;
Console.WriteLine("Enter two inputs");
a = Convert.ToString(Console.ReadLine());
b = Console.ReadLine();
f1 = find(a);
f2 = find(b);
if (f1 == 0 && f2 == 0)
{
x = Convert.ToInt32(a);
y = Convert.ToInt32(b);
Console.WriteLine("Two inputs r number \n so that addition of these text box is= " + (x + y).ToString());
}
else
Console.WriteLine("One or two inputs r string \n so that concatenation of these text box is = " + (a + b));
Console.ReadKey();
}
static int find(string s)
{
string s1 = "";
int f;
for (int i = 0; i < s.Length; i++)
for (int j = 0; j <= 9; j++)
{
string c = j.ToString();
if (c[0] == s[i])
{
s1 += c[0];
}
}
if (s == s1)
f = 0;
else
f = 1;
return f;
}
所有的答案都很有用。但是在寻找数值为12位数或更多的解决方案时(在我的情况下),然后在调试时,我发现以下解决方案很有用:
double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);
结果变量会给你true或false。
如果你想检查一个字符串是否是一个数字(我假设它是一个字符串,因为如果它是一个数字,你知道它是1)。
没有正则表达式和 尽可能多地使用微软的代码
你还可以:
public static bool IsNumber(this string aNumber)
{
BigInteger temp_big_int;
var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
return is_number;
}
这将解决通常的麻烦:
开头是负(-)或正(+ BigIntegers不会解析带小数点的数字。(因此:BigInteger.Parse("3.3")将抛出异常,而TryParse将返回false) 没有搞笑的非数字 适用于数字大于Double通常用法的情况。TryParse
您必须向System添加一个引用。数字和有 使用System.Numerics;名列全班第一(好吧,我猜第二名是额外奖励:)
Regex rx = new Regex(@"^([1-9]\d*(\.)\d*|0?(\.)\d*[1-9]\d*|[1-9]\d*)$");
string text = "12.0";
var result = rx.IsMatch(text);
Console.WriteLine(result);
检查字符串是否为uint, ulong或只包含数字1 .(点)和数字 样例输入
123 => True
123.1 => True
0.123 => True
.123 => True
0.2 => True
3452.434.43=> False
2342f43.34 => False
svasad.324 => False
3215.afa => False