2012-10-19 30 views
-3

我是新來的c#編程。有人可以幫我找出如何在分割之前檢查字符串是否爲空。我使用了下面的方法,但如果字符串爲null,則會引發空引用錯誤。如何在分割字符串之前檢查空值

string[] splittedString=orgString.Split(','); 
+0

你的問題中缺少的是當字符串爲空時你想要做什麼。 –

回答

6
string cleanedString = orgString ?? ""; 
string[] splittedString = cleanedString.Split(','); 
+0

+1最好的方法 –

+2

我不喜歡這個答案。這將隱藏空字符串。大多數情況下,如果字符串爲空,則可能在代碼的早期出現問題。在方法開始時未檢查無效, –

1
String.IsNullOrEmpty(string) 

或只是空

if (string == null) 
+0

c#中沒有'==='運算符 – mlorbetske

+0

哈亞,對不起,壞(好)習慣... –

5

我會建議使用String.IsNullOrWhiteSpace,因爲這如果字符串爲null,不僅會檢查,而且還確保它不空。

string orgString = null; 

if (!String.IsNullOrWhiteSpace(orgString)) 
{ 
    string[] splittedString = orgString.Split(','); 
}