Jon*_*ood 63
只需检查每个角色.
bool IsAllDigits(string s)
{
foreach (char c in s)
{
if (!char.IsDigit(c))
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
或者使用LINQ.
bool IsAllDigits(string s)
{
return s.All(char.IsDigit);
}
Run Code Online (Sandbox Code Playgroud)
如果您想知道输入到程序中的值是否表示有效的整数值(在范围内int),您可以使用TryParse().请注意,此方法与检查字符串是否仅包含数字不同.
bool IsAllDigits(string s)
{
return int.TryParse(s, out int i);
}
Run Code Online (Sandbox Code Playgroud)
你的问题不明确..在字符串中是允许的吗?被¼允许吗?
string source = GetTheString();
//only 0-9 allowed in the string, which almost equals to int.TryParse
bool allDigits = source.All(char.IsDigit);
bool alternative = int.TryParse(source,out result);
//allow other "numbers" like ¼
bool allNumbers = source.All(char.IsNumber);
Run Code Online (Sandbox Code Playgroud)
如果你想使用正则表达式,你将不得不使用这样的东西:
string regExPattern = @"^[0-9]+$";
System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(regExPattern);
return pattern.IsMatch(yourString);
Run Code Online (Sandbox Code Playgroud)