拆分字符串并乘以8

时间:2013-02-17 03:01:23

标签: c#

我遇到了麻烦。用户需要输入一个字符串然后我需要计算字符串并乘以相同的字符串。例如,如果用户输入了字符串,则快速棕色狐狸跳过懒狗;
输出应该如下所示,= 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个单词。我试图比较每个字符串,以确定它们是否相同,但无法这样做。

5 个答案:

答案 0 :(得分: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};

答案 1 :(得分: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);
        }

答案 2 :(得分:0)

我会通过使用两个List

来做到这一点
List<String> words  = new List<String>();
List<int> weight = new List<int>();

当你浏览字符串时,你只在单词List中添加唯一的单词,然后权重列表的相应索引增加1;

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

的长度

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

  • 自动添加第一个字符串
  • 对于之后的每个字符串,执行words.Contains(string [x])
  • 如果它不包含它,那么添加它
  • 如果确实包含它,则执行words.indexOf(string [x])
  • 然后在权重列表中增加相应的索引

答案 3 :(得分: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)
                    });

答案 4 :(得分:0)

你可以试试这个:

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