Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用c#计算字符串数组中的单词出现次数?_C# - Fatal编程技术网

如何使用c#计算字符串数组中的单词出现次数?

如何使用c#计算字符串数组中的单词出现次数?,c#,C#,我是编程新手,我正在尝试编写一个程序,它接收字符串数组(数组的每个索引都是一个单词),然后计算字符串中每个单词的出现次数。这就是我到目前为止所做的: string[] words = { "which", "wristwatches", "are", "swiss", "wristwatches" };

我是编程新手,我正在尝试编写一个程序,它接收字符串数组(数组的每个索引都是一个单词),然后计算字符串中每个单词的出现次数。这就是我到目前为止所做的:

        string[] words = 
        {
            "which", 
            "wristwatches", 
            "are", 
            "swiss", 
            "wristwatches"
        };

        Array.Sort (words);
        for (int i = 0; i < words.Length; i++) 
        {
            int count = 1;
            for(int j = 1; j < words.Length; j++)
            {
                if (words [i] == words [j])
                {
                    count++;
                }
            }
            Console.WriteLine ("{0}   {1}", words[i], count);
        } 
string[]字=
{
“哪个”,
“手表”,
“是”,
“瑞士”,
“手表”
};
数组。排序(单词);
for(int i=0;i
理想情况下,我希望输出类似于:

是1

瑞士1

哪一个1


腕表2

代码的问题是(1)重复计数和(2)跳过嵌套循环中的初始元素

你重复计算,因为你忽略了当
i==j
时的情况;由于设置了
int j=1
,因此跳过了初始元素

最短的解决方案是使用LINQ,如下所示:

var counts = words
    .GroupBy(w => w)
    .Select(g => new {Word = g.Key, Count = g.Count()})
    .ToList();
foreach (var p in counts) {
    Console.WriteLine("Word '{0}' found {1} times", p.Word, p.Count);
}
现在,您可以按如下方式打印结果:

var counts = words
    .GroupBy(w => w)
    .Select(g => new {Word = g.Key, Count = g.Count()})
    .ToList();
foreach (var p in counts) {
    Console.WriteLine("Word '{0}' found {1} times", p.Word, p.Count);
}

为了您的理解和使用

int Duplicate=words.Lenth+1//任何不在字符串数组范围内的值
for(int i=0;i

这将不会再次打印相同的值。

当然有更有效的处理方法(看看dasblinkenlight的答案,这是一个非常好的答案),但如果您希望保留相对相同的代码,您应该将第二个for循环更改为以下内容:

var occrs = words.GroupBy(x => x.ToLower())
               .ToDictionary(g => g.Key, g => g.Count());
foreach(var pair in occrs)
    Console.WriteLine(pair.Key + " " +pair.Value);
for(int j = i+1; j < words.Length; j++)
{
    if (words [i] == words [j])
    {
        count++;
    }
    else break;
}
for(int j=i+1;j
以下是我所做的两项更改:

1) 您应该将j初始化为i+1;您需要检查其余的字符串是否等于字[i],其余的字符串将从i+1开始,而不是从1开始(除非i=0)


2) 为了提高效率,如果两个字符串不相等,则需要中断第二个循环;由于您按字母顺序对数组进行了排序,因此如果当前正在查看的单词不相等,则后面的单词也不会相等。

请使用字典数据结构。在这里,字典将关键字存储为单词,值存储为单词计数。在字典中插入所有单词。如果插入的单词是新单词,请将单词键值设置为1,否则将单词键值增加1

        Dictionary<string, int> wordCount = new Dictionary<string, int>();

        // Insert a word in the dictionary if it exits, otherwise increment 
        //the count of the word

        for (int i = 0; i < words.Length; i++)
        {
            try
            {
                wordCount.Add(words[i], 1);
            }
            catch (Exception)
            {
                wordCount[words[i]] += 1;
            }
        }

        // display word and it's corresponding word count

        foreach (var item in wordCount)
        {
            Console.WriteLine ("{0}   {1}", item.Key, item.Value);
        }
Dictionary wordCount=new Dictionary();
//如果存在单词,则在字典中插入该单词,否则递增
//字数
for(int i=0;i
很酷。你需要什么帮助?嗯,我似乎不能得到正确的输出,当我运行它时,我得到的是1瑞士2哪2手表3手表3@MitchWheat我的意思是“最短”-这是一个单独的语句:)嗯,我还没有使用或见过LINQ,但这很有趣!:)有没有办法修改我已经编写的代码,或者它会太复杂和混乱?@user1822739绝对-添加
if(I!=j&&words[I]==words[j])
以避免重复计算同一个单词,并在嵌套循环中使用
int j=0
来修复代码。哇,这很有意义!感谢您的详细解释:)string.Compare方法是一种非常有用的方法,谢谢您hey@user1822739检查我编辑的答案。现在,这将不会在控制台上再次打印重复的值。