2015-11-05 273 views
1

我必須計算來自給定輸入文本的每個單詞出現在其中的次數。 而我卡住的東西:字符外殼差異應該被忽略。忽略區分大小寫

例如: 「你是here.You你」 - >輸出:

are=1 
here=1 
You=3 

我做了什麼:

string text = "You are here.You you"; 
IDictionary<string, int> wordsCount = new SortedDictionary<string, int>(); 
string[] words = text.Split(' ',',','.','-','!'); 

foreach (string word in words) 
{ 
    int count = 1; 
    if (wordsCount.ContainsKey(word)) 
     count = wordsCount[word] + 1; 
    wordsCount[word] = count; 
} 
var items = from pair in wordsCount 
      orderby pair.Value ascending 
      select pair; 
foreach (var p in items) 
{ 
    Console.WriteLine("{0} -> {1}", p.Key, p.Value); 
} 

有一個機會,使這成爲可能,而不檢查手動給定文本中的每個單詞?例如,如果我有一個很長的段落,不使用特定的方法檢查每個單詞?就在string[] words = text.Split(' ',',','.','-','!');前行

text = text.ToLower(); 

回答

1

只需添加

for(i = 0; text[i] != '\0'; i++){ 
    text[i] = text[i].ToLower(); 
} 

但作爲text是一個字符串,只是做。 然後享受!

+0

對不起,我應該放在toLower前面工作? – Nero

+0

我沒明白... –

+0

你寫道:text [i] = tolower(text [i])。這是什麼「tolower」? – Nero

0

linq怎麼樣?

var text = "You are here.You you"; 
var words = text.Split(' ', ',', '.', '-', '!'); 

words 
    .GroupBy(word => word.ToLowerInvariant()) 
    .OrderByDescending(group => group.Count()) 
    .ToList() 
    .ForEach(g=> Console.WriteLine(g.Key + "=" + g.Count()));