C# 你是如何把一个字符串组织起来的?这个词在c中出现了多少次?

C# 你是如何把一个字符串组织起来的?这个词在c中出现了多少次?,c#,visual-studio,C#,Visual Studio,好的,我不知道该怎么做,我也试着查了查怎么做,但没有什么好结果,所以我会在这里问。所以我想做的是: string input = TextEditor.text; <-- this is in windows form application and The "TextEditor" is the textbox for input 我想从texct框中获取输入的字符串,然后将其拆分,使每个单词位于每一行上,如下所示: 如果input=hi,我的名字是 输出应为: hi: 1 my

好的,我不知道该怎么做,我也试着查了查怎么做,但没有什么好结果,所以我会在这里问。所以我想做的是:

string input = TextEditor.text;    <-- this is in windows form application and
The "TextEditor" is the textbox for input
我想从texct框中获取输入的字符串,然后将其拆分,使每个单词位于每一行上,如下所示:

如果input=hi,我的名字是

输出应为:

hi: 1
my: 1
name: 1
is: 2 <-- if the word is said it shouldn't be repeated.

谁能帮帮我吗?我是一个真正的新手,我完全迷路了。我还没有任何代码,因为我不知道如何做到这一点

将输入字符串拆分为数组,然后使用该数组构建字典。如果单词已经在字典中,则增加它。否则,将其与初始值1相加

    string input = TextEditor.text;
    string[] inputWords = input.Split(' ');
    Dictionary<string, int> wordCounts = new Dictionary<string, int>();
    foreach (string word in inputWords)
    {
        if (wordCounts.ContainsKey(word))
        {
            wordCounts[word]++;
        }
        else
        {
            wordCounts.Add(word, 1);
        }
    }
使用Linq和Count:

string inputText = "hi my name is is";

var words = inputText.Split(' ').ToList();

var wordGroups = words.GroupBy(w => w).Select(grp => new {
                                                Word  = grp.Key,
                                                Count   = grp.Count()
                                            });

string outputText = string.Join("\n", wordGroups.Select(g => string.Format("{0}:\t{1}", g.Word, g.Count)));
/*
hi:  1
my:  1
name:  1
is:  2
*/

谢谢,我会试试看的。你在字典里查这个词两遍了。一次检查单词是否存在,然后增加计数。请看:非常感谢