2013-02-17 84 views
0

我遇到問題了。用戶需要輸入一個字符串,然後我需要對字符串進行計數並乘以相同的字符串。例如,如果用戶輸入字符串快速棕色狐狸跳過懶狗;
輸出應該是這樣的,在= 22%快速= 11%褐色= 11%狐= 11%躍過= 11%爲lazy = 11%的狗= 11%= 11%拆分字符串並乘以8

這裏是我的代碼

string phrase = "The quick brown fox jumps over the lazy dog"; 
     string[] arr1 = phrase.Split(' '); 


     for (int a = 0; a < arr1.Length; a++) 
     { 
      Console.WriteLine(arr1[a]); 
     } 



     Console.ReadKey(); 

該值爲22%,它使用該公式計算得出,2/9 * 100. 2因爲「the」被使用了兩次,除以9,因爲字符串中有9個單詞。我正在比較每個字符串以確定它們是否相同,但無法這樣做。

+0

到目前爲止,你寫代碼,以分割的字符串。你仍然需要編寫代碼來處理這些單詞。這是怎麼回事? – 2013-02-17 03:05:28

+1

你可以使用'Dictionary ',文檔:http://msdn.microsoft.com/en-ca/library/xfhwa508.aspx,或者你可以在你的數組中使用'GroupBy' linq方法。 – Matthew 2013-02-17 03:08:20

+0

所以你想要一個單詞的直方圖。也許更新標題爲「如何從短語獲取單詞的直方圖」。 – ja72 2013-02-17 03:17:20

回答

3

強制性的LINQ版本:

string phrase = "The quick brown fox jumps over the lazy dog"; 
string[] words = phrase.Split(' '); 
var wc = from word in words 
     group word by word.ToLowerInvariant() into g 
     select new {Word = g.Key, Freq = (float)g.Count()/words.Length * 100}; 
+0

Dezza,如果您不熟悉LINQ,那麼請檢查一下,因爲afrischke的解決方案非常簡單,而且使用LINQ可以使編碼變得簡單快捷:http://msdn.microsoft.com/en-us/庫/ vstudio/bb397926.aspx – Rethunk 2013-02-17 03:19:56

0

我會通過使用兩個目錄

List<String> words = new List<String>(); 
List<int> weight = new List<int>(); 

當你通過你的字符串只添加獨特的單詞的話清單,然後權重表的相應指數被增加1做到這一點;

  • 然後,當你做,你可以通過你的字符串的長度除以每個權重值的[]

    至於獲得唯一值,你可以通過執行以下操作做到這一點添加第一個字符串後做words.Contains(字符串[X])

  • 如果它不包含它然後將其添加
  • 如果它不包含自動
  • 列出每串然後它做words.indexOf(字符串[X])
  • 然後增加相應的指數權重表
+0

我會試試這個 – 2013-02-17 03:11:44

+0

謝謝,希望它適合你。如果確實如此,請記得點名並選擇答案。祝你好運! – 2013-02-17 03:14:36

0
string phrase = "The quick brown fox jumps over the lazy dog"; 
var parts = phrase.Split(' '); 
var wordRatios = parts 
        .GroupBy(w => w.ToLower()) 
        .Select(g => new{ 
         word = g.Key, 
         pct = Math.Round(g.Count() * 100d/parts.Length) 
        }); 
+0

哦。就像@afrisdhke一樣。 – spender 2013-02-17 03:21:25

1

LINQ使用最少的!

 string phrase = "The quick brown fox jumps over the lazy dog"; 
     string[] words = phrase.ToLower().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 

     var distinct_words = words.Distinct().ToArray(); 
     foreach (string word in distinct_words) 
     { 
      int count = words.Count(wrd => wrd == word); 
      Console.WriteLine("{0} = {1} % ", word, count * 100/words.Length); 
     } 

或者

 string phrase = "The quick brown fox jumps over the lazy dog"; 
     string[] words = phrase.ToLower().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 
     var needed_lines = from word in words.Distinct() let count = words.Count(wrd => wrd == word) select String.Format("{0} = {1} % ", word, count * 100/words.Length); 

     foreach (string neededLine in needed_lines) 
     { 
      Console.WriteLine(neededLine); 
     } 
0

你可以試試這個:

var yourarr = phrase.Split(' ').GroupBy(word => word.ToUpper()).Select(w => ((w.Count()*100/ phrase.Split(' ').Distinct().Count())).ToString()+"%");