Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

search

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?"
like image 693
Sinaesthetic Avatar asked Sep 30 '10 08:09

Sinaesthetic


3 Answers

var containsdigit = somestring.Any(char.IsDigit);
like image 174
leppie Avatar answered Oct 11 '22 06:10

leppie


You could use String.IndexOfAny as:

bool isNumeric = mystring.IndexOfAny("0123456789".ToCharArray()) > -1;
like image 26
Hans Olsson Avatar answered Oct 11 '22 07:10

Hans Olsson


You could create an extension method for string and use a combination of LINQ and the Char.IsNumber function e.g.

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    
like image 41
James Avatar answered Oct 11 '22 06:10

James