我一直在处理这个问题几天,我试图完成一个控制台应用程序,我们被提示输入一个我们自己的字符串和输出列出每个独特的角色并在其后面进行计数。在结果结束时,会显示一个计数,显示找到了多少个唯一字符。尽管是大写还是不是大写,但所有内容都被转换为小写。他们的关键是使用集合。这是我到目前为止。尽管事实上我使用if语句来捕捉它们,但我的输出在结果中显示了两个空格字符。任何人都可以指出我忽视的一个概念吗?我是用字母表中的每个字母也从输入中计算字符时,在输出中计算空格字符
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class LetterCountTest
{
public static void Main(string[] args)
{
// create sorted dictionary based on user input
SortedDictionary<string, int> dictionary = CollectLetters();
// display sorted dictionary content
DisplayDictionary(dictionary);
} // end Main
// create sorted dictionary from user input
private static SortedDictionary<string, int> CollectLetters()
{
// create a new sorted dictionary
SortedDictionary<string, int> dictionary =
new SortedDictionary<string, int>();
Console.WriteLine("Enter a string: "); // prompt for user input
string input = Console.ReadLine(); // get input
// split every individual letter for the count
string[] letters = Regex.Split(input, "");
// processing input letters
foreach (var letter in letters)
{
string letterKey = letter.ToLower(); // get letter in lowercase
if (letterKey != " ") // statement to exclude whitespace count
{
// if the dictionary contains the letter
if (dictionary.ContainsKey(letterKey))
{
++dictionary[letterKey];
} // end if
else
// add new letter with a count of 1 to the dictionary
dictionary.Add(letterKey, 1);
}
} // end foreach
return dictionary;
} // end method CollectLetters
// display dictionary content
private static void DisplayDictionary<K, V>(
SortedDictionary<K, V> dictionary)
{
Console.WriteLine("\nSorted dictionary contains:\n{0,-12}{1,-12}",
"Key:", "Value:");
// generate output for each key in the sorted dictionary
// by iterating through the Keys property with a foreach statement
foreach (K key in dictionary.Keys)
Console.WriteLine("{0,-12}{1,-12}", key, dictionary[key]);
Console.WriteLine("\nsize: {0}", dictionary.Count);
Console.ReadLine();
} // end method DisplayDictionary
} // end class LetterCountTest
我的输出状态具有上述的“a”和它的两个实例一个空白。我不知道这是从哪里来的,但我的猜测是它计数空字符或回车。我用的是串...
敏捷的棕色狐狸跳过懒狗
除了一次计数每一个字母,它计算电子三倍的H两次,邻四次, r两次,t两次,u两次。
'Regex.Split(输入, “”);'是更好的写作'input.ToCharArray()' – user2864740
你得到之初,因为你的'Regex.Split(输入的空字符串和结束,“”)'。切换到建议的答案,或将您的if语句更改为if(letterKey!=“”&& letterKey!=“”)应该可以解决问题 – itsananderson
您是男人Will =) 现在,另一个条件。我不确定它在做什么,但现在我明白了。再次感谢您的帮助! – user1086365