11

I am having an string like this

string str = "dfdsfdsf8fdfdfd9dfdfd4"

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

balaweblog
  • 14,982
  • 28
  • 73
  • 95

8 Answers8

32

What about a regular expression:

bool val = System.Text.RegularExpressions.Regex.IsMatch(str, @"\d");
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
  • And also have a look at John M Gant answer: http://stackoverflow.com/questions/894263/how-to-identify-if-string-contain-a-number – Junior Mayhé Jan 02 '12 at 14:40
9

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"); 
splattne
  • 102,760
  • 52
  • 202
  • 249
6

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;
Timothy Khouri
  • 31,315
  • 21
  • 88
  • 128
4
str.ToCharArray().Any(x => char.IsNumber(x));
Kamal
  • 157
  • 6
  • 1
    Thanks to [`String.IEnumerable(Of Char).GetEnumerator`](http://msdn.microsoft.com/en-us/library/cc672334.aspx), you actually don't even need the `.ToCharArray()` as the string is automatically cast as an enumerable of type char. – KyleMit May 21 '14 at 20:42
1

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

andrewtatham
  • 1,093
  • 9
  • 10
0
str.ToCharArray().Any(char.IsNumber)
skynet
  • 9,898
  • 5
  • 43
  • 52
TriStar
  • 173
  • 1
  • 4
  • 14
  • `Any()` takes a predicate, so this will not compile. Also, this exact answer was [already provided by Kamal](http://stackoverflow.com/a/11145727/1366033) – KyleMit May 21 '14 at 20:37
  • Actually that method group is a valid predicate, so it does compile, and this answer is not quite the same as Kamals – andrewtatham Jul 04 '17 at 12:04
0

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;
GeekyMonkey
  • 12,478
  • 6
  • 33
  • 39
  • Good God, that's hideous. If I find that in a code review I'd (a) excise it; (b) excise you. – endian Nov 06 '08 at 10:34
  • 2
    The code isn't bad - except you should use "Any()" instead of "Count() > 0" - that way you short circuit and don't need to evaluate the rest of the list since you know you've hit 'true' already. – Timothy Khouri Feb 01 '12 at 17:12
0

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
            }
        }
Arief
  • 6,055
  • 7
  • 37
  • 41