2009-10-08 14 views

Odpowiedz

145
"abc3def".Any(c => char.IsDigit(c)); 

Aktualizacja: jak @Cipher wskazał, że w rzeczywistości może być jeszcze krótszy:

"abc3def".Any(char.IsDigit); 
+0

Nie mogłem znaleźć wszystkich metod() i Any(), chociaż używam 4.5 struktura. Czy wiesz dlaczego? – cihata87

+4

@ Cihata87 upewnij się, że dodałeś 'using System.Linq;' w górnej części pliku kodu. –

12

Spróbuj

public static bool HasNumber(this string input) { 
    return input.Where(x => Char.IsDigit(x)).Any(); 
} 

Wykorzystanie

string x = GetTheString(); 
if (x.HasNumber()) { 
    ... 
} 
+3

Lub po prostu 'input.Any (x => Char.IsDigit (x));' –

+0

@Mehrdad, tak, ciągle zapominam o tym przeciążeniu – JaredPar

8

lub możliwe przy użyciu Regex:

string input = "123 find if this has a number"; 
bool containsNum = Regex.IsMatch(input, @"\d"); 
if (containsNum) 
{ 
//Do Something 
} 
-1

Jak o tym:

bool test = System.Text.RegularExpressions.Regex.IsMatch(test, @"\d"); 
-1
string number = fn_txt.Text; //textbox 
     Regex regex2 = new Regex(@"\d"); //check number 
     Match match2 = regex2.Match(number); 
     if (match2.Success) // if found number 
     { **// do what you want here** 
      fn_warm.Visible = true; // visible warm lable 
      fn_warm.Text = "write your text here "; /
     } 
+0

Nie sądzę, że to naprawdę odpowiada na pytanie, ponieważ pytanie było interesujące w krótkich pytaniach, a jest ich już wiele, które są o wiele bardziej zwięzłe. – JHobern

Powiązane problemy