[英]How do I count the number of noise words in a string?
假設我有一個干擾詞列表...
string[] noise = new[] {"and", "it", "in"}; // etc, etc
...而且我有一個字符串s
。 我想知道s
多少個干擾詞。
我知道可以通過在空間上分割s
,然后循環遍歷所得數組檢查是否存在noise
來做到這一點,但這似乎是一種效率很低的方法。 感覺應該有一種整齊的RegEx或Linq方式來做到這一點。
有什么建議么?
LINQ並不比循環更有效,但通常更易讀和簡潔,我想這就是您想要的。 在這種情況下,您可以使用Enumerable.Count
和Contains
:
int countNoiseWords = s.Split().Count(noise.Contains);
不區分大小寫的方式:
int countNoiseWords = s.Split()
.Count(w => noise.Contains(w, StringComparer.InvariantCultureIgnoreCase));
如果noise
-list很長,則應考慮使用HashSet<string>
而不是列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.