【发布时间】:2011-02-08 11:59:38
【问题描述】:
我需要我的应用程序根据所选文本是否包含字母或除数字以外的任何内容执行操作。不要这样做。
如何判断字符串是字母还是数字?
很简单,但我不会写这段代码。
【问题讨论】:
-
请说得更具体一些,你想知道它是只包含字母还是只包含数字?
-
@atticae - 很难说,但在我们的答案中,他可能会找到他可以使用的东西。
标签: c# datagridview
我需要我的应用程序根据所选文本是否包含字母或除数字以外的任何内容执行操作。不要这样做。
如何判断字符串是字母还是数字?
很简单,但我不会写这段代码。
【问题讨论】:
标签: c# datagridview
你可以尝试这样做:
string myString = "100test200";
long myNumber;
if( long.TryParse( myString, out myNumber ){
//text contains only numbers, and that number is now put into myNumber.
//do your logic dependent of string being a number here
}else{
//string is not a number. Do your logic according to the string containing letters here
}
如果您想查看字符串是否包含一个或多个数字,而不是所有数字,请改用此逻辑。
if (myString.Any( char.IsDigit )){
//string contains at least one digit
}else{
//string contains no digits
}
【讨论】:
static bool IsNumeric(string str)
{
foreach(char c in str)
if(!char.IsDigit(c))
return false;
return true;
}
【讨论】:
str.All(char.IsDigit); ;)
你可以用正则表达式来实现这一点
string str = "1029";
if(Regex.IsMatch(str,@"^\d+$")){...}
【讨论】: