简体   繁体   English

C#:有没有办法在不使用正则表达式的情况下搜索数字的字符串?

[英]C#: Is there a way to search a string for a number without using regex?

Is there a way to check to see if a string contains any numeric digits in it without using regex?有没有办法在不使用正则表达式的情况下检查字符串中是否包含任何数字? I was thinking of just splitting it into an array and running a search on that, but something tells me there is an easier way:我正在考虑将其拆分为一个数组并对其进行搜索,但有些东西告诉我有一种更简单的方法:

//pseudocode
string aString = "The number 4"

If (aString contains a number) Then enter validation loop
Else return to main

//output
"The string contains a number. Are you sure you want to continue?"
var containsdigit = somestring.Any(char.IsDigit);

您可以将String.IndexOfAny用作:

bool isNumeric = mystring.IndexOfAny("0123456789".ToCharArray()) > -1;

You could create an extension method for string and use a combination of LINQ and the Char.IsNumber function eg您可以为字符串创建一个扩展方法并使用 LINQ 和Char.IsNumber函数的组合,例如

public static class StringExt
{
    public static bool ContainsNumber(this string str)
    {
        return str.Any(c => Char.IsNumber(c)); 
    }
}

Then your logic would look like:然后你的逻辑看起来像:

//pseudocodestring 
string str = "The number 4";
If (aString.ContainsNumber())
    enter validation    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM