To check whether the string value has numeric value or not in C#

老子叫甜甜 提交于 2019-12-04 17:59:12

问题


I am having an string like this

string str = "dfdsfdsf8fdfdfd9dfdfd4"

I need to check whether the string contains number by looping through the array.


回答1:


What about a regular expression:

bool val = System.Text.RegularExpressions.Regex.IsMatch(str, @"\d");



回答2:


If you are looking for an integer value you could use int.TryParse:

int result;
if (int.TryParse("123", out result))
{
    Debug.WriteLine("Valid integer: " + result);
}
else
{
    Debug.WriteLine("Not a valid integer");
}

For checking a decimal number, replace int.TryParse with Decimal.TryParse. Check out this blog post and comments "Why you should use TryParse() in C#" for details.

If you need decimal numbers, you could alternatively use this regular expression:

return System.Text.RegularExpressions.Regex.IsMatch(
   TextValue, @"^-?\d+([\.]{1}\d*)?$");

And finally another alternative (if you are not religiously against VB.NET), you could use the method in the Microsoft.VisualBasic namespace:

Microsoft.VisualBasic.Information.IsNumeric("abc"); 



回答3:


If you're going to loop through the string, DON'T use int.TryParse... that's way too heavy. Instead, use char.IsNumber();

example:

foreach (char c in myString)
    if (char.IsNumber(c))
        return true;



回答4:


str.ToCharArray().Any(x => char.IsNumber(x));



回答5:


Combining parts of Kamals answer and Tristars answers give...

str.Any(char.IsNumber)

which I think is the most succinct and readable way, instead of a regex




回答6:


If you're a linq junkie like me, you'd do it this way

string s = "abc1def2ghi";
bool HasNumber = (from a in s.ToCharArray() where a >= '0' && a <= '9' select a).Count() > 0;



回答7:


in C# 2.0, try this:

        string str = "dfdsfdsf8fdfdfd9dfdfd4";

        for (int i = 0; i < str.Length; i++)
        {
            int result;
            if (int.TryParse(str[i].ToString(), out result))
            {
                //element is a number            
            }
            else
            {
                // not a number
            }
        }



回答8:


str.ToCharArray().Any(char.IsNumber)


来源:https://stackoverflow.com/questions/268120/to-check-whether-the-string-value-has-numeric-value-or-not-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!