2015-02-23 48 views
1

我正在寫一個簡單的控制檯應用程序來允許我計算每個唯一字的出現次數。例如,控制檯將允許用戶輸入一個句子,一旦按下輸入系統就應該計算每個單詞出現的次數。到目前爲止,我只能計數字符。任何幫助,將不勝感激。計算文件中每個唯一字的出現c#

class Program 
{ 
    static void Main(string[] args) 
    { 

     Console.WriteLine("Please enter string"); 
     string input = Convert.ToString(Console.ReadLine()); 
     Dictionary<string, int> objdict = new Dictionary<string, int>(); 
     foreach (var j in input) 
     { 
      if (objdict.ContainsKey(j.ToString())) 
      { 
       objdict[j.ToString()] = objdict[j.ToString()] + 1; 
      } 
      else 
      { 
       objdict.Add(j.ToString(), 1); 
      } 
     } 
     foreach (var temp in objdict) 
     { 
      Console.WriteLine("{0}:{1}", temp.Key, temp.Value); 
     } 
     Console.ReadLine(); 
    } 
} 
+0

使用'foreach'在字符串上會迭代每個_character_。迭代你需要用空格拆分的每個單詞(去除標點符號後) – 2015-02-23 17:16:13

+0

你正在嘗試編寫代碼的好東西...現在,如果你澄清你有什麼問題會使問題變得很好(我假設你沒有麻煩與http://www.bing.com/search?q=c%23+split+sentence+into+words) – 2015-02-23 17:16:40

+0

嘗試foreach(var j in input.Split(「」))來分割每個輸入字符串空間。這會給你一大堆話語。那麼你的邏輯應該仍然有效。 – KevDevMan 2015-02-23 17:17:35

回答

0

試試這個方法:

private void countWordsInALIne(string line, Dictionary<string, int> words) 
{ 
    var wordPattern = new Regex(@"\w+"); 

    foreach (Match match in wordPattern.Matches(line)) 
    { 
     int currentCount=0; 
     words.TryGetValue(match.Value, out currentCount); 

     currentCount++; 
     words[match.Value] = currentCount; 
    } 
} 

調用上面的方法是這樣的:

var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase); 

countWordsInALine(line, words); 

在單詞詞典中,你會發現字(密鑰),其次數頻率沿(值)。

0

只需調用Split方法傳遞單個空間(假設單詞由單個空格分隔),並且它將收集每個單詞,然後使用與您具有的相同邏輯迭代集合的每個元素。

class Program 
{ 
    static void Main(string[] args) 
    { 

     Console.WriteLine("Please enter string"); 
     string input = Convert.ToString(Console.ReadLine()); 
     Dictionary<string, int> objdict = new Dictionary<string, int>(); 
     foreach (var j in input.Split(" ")) 
     { 
      if (objdict.ContainsKey(j)) 
      { 
       objdict[j] = objdict[j] + 1; 
      } 
      else 
      { 
       objdict.Add(j, 1); 
      } 
     } 
     foreach (var temp in objdict) 
     { 
      Console.WriteLine("{0}:{1}", temp.Key, temp.Value); 
     } 
     Console.ReadLine(); 
    } 
} 
0

您需要將字符串拆分爲空格(或任何其他您認爲要分隔字符的字符)。嘗試改變環路這樣:

foreach (string Word in input.Split(' ')) { 

} 
1

嘗試......

var theList = new List<string>() { "Alpha", "Alpha", "Beta", "Gamma", "Delta" }; 

theList.GroupBy(txt => txt) 
    .Where(grouping => grouping.Count() > 1) 
    .ToList() 
    .ForEach(groupItem => Console.WriteLine("{0} duplicated {1} times with these values {2}", 
     groupItem.Key, 
     groupItem.Count(), 
     string.Join(" ", groupItem.ToArray()))); 
     Console.ReadKey(); 

http://omegacoder.com/?p=792