如何检查.NET中字符串是否是一个数字或不? [英] How to check whether a string in .NET is a number or not?
问题描述
如何检查.NET中给定的字符串是否为数字或不?
How to check whether a given string in .NET is a number or not?
测试1 - 为字符串
test1 - is string
1232 - 编号为
1232 - is number
测试 - 为字符串
tes3t - 为字符串
tes3t - is string
2323k - 为字符串
2323k - is string
4567 - ?编号为
4567 - is number
我怎样才能做到这一点使用系统功能
How can I do this using system functions?
推荐答案
您可以写一个简单的循环,测试每个字符。
You can write a simple loop that tests each character.
bool IsNumber(string s)
{
foreach (char c in s)
{
if (!Char.IsDigit(c))
return false;
}
return s.Any();
}
或者你可以使用LINQ。
Or you could use LINQ.
bool IsNumber(string s)
{
return s.Any() && s.All(c => Char.IsDigit(c));
}
如果您更关心的是,如果字符串可以表示为一个 INT
键入比你所有的字符是数字,你可以使用 int.TryParse()
。
If you are more concerned about if the string can be represented as an int
type than you are that all the characters are digits, you can use int.TryParse()
.
bool IsNumber(string s)
{
int i;
return int.TryParse(s, out i);
}
注意::你不会得到太大的帮助如果你不开始接受一些答案的人给你。
NOTE: You won't get much help if you don't start accepting some answers people give you.
这篇关于如何检查.NET中字符串是否是一个数字或不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!