[英]C# numbers and Letters
I need my application to perform an action based on if the selected text is contains letters or anything except numbers dont do that. 我需要我的应用程序根据所选文本是否包含字母或除数字以外的任何内容执行操作。
How can I tell if a string is letters or numbers? 如何判断字符串是字母还是数字?
Its so easy but i can not write this code. 它是如此简单,但我无法编写此代码。
You can try to do it like this: 您可以尝试这样做:
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 you want to see if the string contains one or more digits, and not all digits, use this logic instead. 如果要查看字符串是否包含一个或多个数字,而不是全部数字,请改用此逻辑。
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;
}
you could achieve this with a regular expression 你可以用正则表达式来实现
string str = "1029";
if(Regex.IsMatch(str,@"^\d+$")){...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.