Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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#_String_Count_Words - Fatal编程技术网

C# 计算字符串中出现的单词数

C# 计算字符串中出现的单词数,c#,string,count,words,C#,String,Count,Words,我在.NETC中有一个项目,我必须计算字符串中出现的单词数。我得到一个KeyNotFoundException,在这个点上,我递增变量以显示一个单词被重复了多少次。 代码如下:向下滚动查看错误 public static Dictionary<string, int> Process(string phrase) { Dictionary<string, int> wordsAndCount = new Dictionary<string, int>(

我在.NETC中有一个项目,我必须计算字符串中出现的单词数。我得到一个KeyNotFoundException,在这个点上,我递增变量以显示一个单词被重复了多少次。 代码如下:向下滚动查看错误

public static Dictionary<string, int> Process(string phrase)
{
    Dictionary<string, int> wordsAndCount = new Dictionary<string, int>();

    string[] words = phrase.Replace("\"", "").Replace("'", "").Replace(".", "").Replace(",", "").Replace("\n", "").Split(' ');
    for (int index = 0; index <= words.Length; index++)
    {
        string word = words[index];
        wordsAndCount[word] = wordsAndCount[word] + 1;
    }
    Dictionary<string, int> dictionary = new Dictionary<string, int>();

    foreach (KeyValuePair<string, int> pair in wordsAndCount.OrderByDescending((s) => s.Key))
        dictionary.Add(pair.Key, pair.Value);

    wordsAndCount = dictionary;
    return wordsAndCount;
}

您的循环包含两个问题:

如果某个密钥不存在,则不能使用该密钥对ContainsKey进行测试 你应该循环直到索引
for (int index = 0; index < words.Length; index++)
{
    string word = words[index];
    if(!wordsAndCount.ContainsKey(word))
        wordsAndCount.Add(word, 1);
    else
        wordsAndCount[word]++;
}
试试这个:

字符串A中字符串B的出现次数

var NumberOfOccurrences = A.Split(new string[] { B }, StringSplitOptions.None).Length - 1;

我认为这与错误无关。我们试过了,运气不好,谢谢。这个错误似乎是不言自明的。它说在字典中找不到该键,因为您正在获取尚未设置的键的值。不知道我在这里要做什么…您不必使用索引器请求字典中不存在的键。良好的实现,正在尝试开发该键,但无法实现!不管怎样,谢谢你这能让我做什么?最后一部分
var temp = wordsAndCount.OrderByDescending (ac => ac.Key);
return temp.ToDictionary (t => t.Key, t => t.Value);
var NumberOfOccurrences = A.Split(new string[] { B }, StringSplitOptions.None).Length - 1;