[英]How to validate whether a string contains 1 number or not c# [on hold]
So I'm wondering how do I check if a string contains only 1 number?所以我想知道如何检查一个字符串是否只包含 1 个数字?
For example "hello1" would output true but "hello123" would output false because it has more than 1 number.例如,“hello1”将 output 为真,但“hello123”将 output 为假,因为它有超过 1 个数字。
Please explain it in the most basic way possible, Thanks!请用最基本的方式解释一下,谢谢!
Using Linq, you could do string.Count(x => Char.IsDigit(x))
and check if it's exactly 1.使用 Linq,您可以执行
string.Count(x => Char.IsDigit(x))
并检查它是否正好是 1。
A simple approach is:一个简单的方法是:
bool HasOnlyOneDigit(string input)
{
bool hasDigit = false;
foreach (char l in input) {
if (char.IsDigit(l))
{
if (hasDigit)
return false;
else
hasDigit = true;
}
}
return hasDigit;
}
In opposition to LINQ, this doesn't require to count the whole string.与 LINQ 相反,这不需要计算整个字符串。 After finding the second digit it will stop.
找到第二个数字后,它将停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.