且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算每个字母按字母顺序出现在文本中的次数

更新时间:2023-11-28 16:37:28

首先,您需要保存每个字母的计数。***的方法是使用Dictionary对象

1st you need to save the count for each alphabet. The best way is to make use of Dictionary object

Dictionary< char,int> countOfLetters = new Dictionary< char,int>();

Dictionary<char, int> countOfLetters = new Dictionary<char, int>();

现在你可以使用foreach循环扫描字符串

Now you can scan the string using a foreach loop

foreach(string coScan中的char c) )

foreach(char c in stringToScan)

在循环内你可以检查字符(字母)是否已经添加

Inside the loop you can check if the character(letter) is already added or not

if(countOfLetters.ContainsKey(c))然后你应该增加点数

if(countOfLetters.ContainsKey(c)) then you should increment the count

countOfLetters [c] ++;

countOfLetters[c]++;

否则你需要将它添加到字数为1的

else you need to add it to the dictionary with count 1

countOfLetters.Add(c,1);

countOfLetters.Add(c, 1);

现在你可以使用另一个foreach循环打印结果

Now you can print the result using another foreach loop

foreach( charc in countOfLetters.Keys)

foreach(char c in countOfLetters.Keys)

Console.WriterLine(" Letter" + c +"出现" + countOfLetter [c] .ToString()+" times。" ;);

Console.WriterLine("Letter " + c + " appeared " + countOfLetter[c].ToString() + " times.");

 

希望这会有所帮助!!!

Hope this helps!!!