2009-10-08 107 views

回答

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

更新:作爲@Cipher指出,它實際上可以進行更短:

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

雖然我使用4.5,但是我找不到All()和Any框架。你知道爲什麼嗎? – cihata87 2016-06-09 10:41:48

+4

@ cihata87確保您在代碼文件的頂部添加了'使用System.Linq;'。 – 2016-06-09 13:34:54

12

試試這個

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

使用

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

或者只是'input.Any(x => Char.IsDigit(x));' – 2009-10-08 21:33:02

+0

@Mehrdad,是的,我經常忘記那個過載 – JaredPar 2009-10-08 21:35:17

8

或可能使用正則表達式:

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

如何:

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

我不認爲這真的回答了這個問題,因爲這個問題對短期查詢感興趣,並且已經有很多比這更簡潔的問題了。 – JHobern 2015-10-30 22:00:51

相關問題