2013-11-04 76 views
1

我正在處理一個任務,其中生成從文本文件讀取的字符串對象數組。我不能使用正則表達式\ W操作符,因爲如果一個單詞包含撇號(')或連字符( - )作爲單詞的一部分,則必須包含它。 W分裂在這些令牌上。但是,我需要它將其他所有不是字母的數字(包括數字)分開。所以我的字符串應該包含a-z,A-Z, - ,'格式。如何刪除字符串數組中的空單元格?

我的代碼是在下面,它給了我幾乎正確的輸出,但是我在它讀取行(或新行)結尾的數組中有空單元格。我不知道如何排除這些(\ n \ r),同時保持我的分割。建議嗎?

try 
{ 
    using (StreamReader reader = new StreamReader("file.txt")) 
    { 
     string line; 
     while ((line = reader.ReadLine()) != null) 
     { 
      string[] words = SplitWords(line.ToLower()); 
      foreach (string aString in words) 
      { 
       Console.WriteLine(aString); 
      } 
     } 
    } 
} 
catch (Exception e) 
{ 
    Console.WriteLine("The file could not be read:"); 
    Console.WriteLine(e.Message); 
} 
static string[] SplitWords(string lines) 
{ 
    return Regex.Split(lines, @"[^-'a-zA-Z]"); 
} 

回答

1

試試這個

return Regex.Split(lines, @"[^-'a-zA-Z]") 
           .Where(x=>!string.IsNullOrWhiteSpace(x)).ToArray(); 

使用IsNullOrWhiteSpace並只提取匹配的元素LINQ新陣列

+1

謝謝!這給了我我想要的東西。等待計時器將其標記爲我接受的答案。感謝您的快速響應。 – user2951579

1

你可以有一點點的LINQ做到這一點。使用此排除任何空字符串:

static string[] SplitWords(string lines) 
{ 
    return Regex.Split(lines, @"[^-'a-zA-Z]") 
       .Where(s => s.Length > 0) 
       .ToArray(); 
} 

或者這排除僅由空白的任何字符串:

static string[] SplitWords(string lines) 
{ 
    return Regex.Split(lines, @"[^-'a-zA-Z]") 
       .Where(s => !s.All(Char.IsWhiteSpace)) 
       .ToArray(); 
}