0

我遇到了麻烦。用户需要输入一个字符串,然后我需要对字符串进行计数并乘以相同的字符串。例如,如果用户输入字符串 The quick brown fox jumps over the lazy dog;
输出应该是这样的, = 22% 快速 = 11% 棕色 = 11% 狐狸 = 11% 跳跃 = 11% 超过 = 11% 懒惰 = 11% 狗 = 11%

这是我的代码

 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 个单词。我正在尝试比较每个字符串以确定它们是否相同但无法这样做。

4

5 回答 5

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};
于 2013-02-17T03:17:09.577 回答
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);
        }
于 2013-02-17T03:24:16.403 回答
0

我会通过使用两个列表来做到这一点

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

当你遍历你的字符串时,你只将唯一的单词添加到单词列表中,然后权重列表的相应索引增加 1;

然后,当您完成后,您可以将每个权重值除以字符串的长度 []

至于获取唯一值,您可以通过执行以下操作来完成:

  • 自动将第一个字符串添加到列表中
  • 之后的每个字符串都做 words.Contains(string[x])
  • 如果它不包含它然后添加它
  • 如果确实包含它,则执行 words.indexOf(string[x])
  • 然后增加权重列表中的相应索引
于 2013-02-17T03:07:03.480 回答
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)
                    });
于 2013-02-17T03:20:34.297 回答
0

你可以试试这个:

 var  yourarr = phrase.Split(' ').GroupBy(word => word.ToUpper()).Select(w => ((w.Count()*100/ phrase.Split(' ').Distinct().Count())).ToString()+"%");
于 2013-02-17T03:53:40.763 回答