2016-12-26 128 views
0

我需要檢查數組的最終位置是否等於空格「」。我的代碼下面拋出一個超出範圍的異常和單詞變量包括通過正則表達式模式結束的空間。c# - 檢查數組的位置是否爲空或空格?

代碼:

string[] words = pattern.Split(input); 
int limit = words.Count(); 

if(words[limit] == " ") 
{ limit = limit - 1; } 

回答

1

.Count()返回數組中元素的個數,但第一個元素的索引是0,所以最後指數應words.Count()-1

+0

在這種情況下,最終元素將等於'限制'。如果最終元素==(「」),它如何寫if語句? – Pilling

+0

謝謝。我完全分開了那一個。乾杯。 – Pilling

2
string[] words = pattern.Split(input); 
    int limit = words.Count(); 

    if(words[limit-1] == " ") 
    { limit = limit - 1; } 

的陣列位置需要在使用count()時爲-1。謝謝。

0

您還可以使用下面的代碼。 IsNullOrWhiteSpace方法檢查給定的字符串是否只包含null或空格字符。

string[] words = pattern.Split(input); 
    int limit = words.Length; 

    if(String.IsNullOrWhiteSpace(words[limit-1])) 
    { 
     limit-=1; //edit value of limit based on your own logic 
    }