我一直在處理這個問題幾天,我試圖完成一個控制檯應用程序,我們被提示輸入一個我們自己的字符串和輸出列出每個獨特的角色並在其後面進行計數。在結果結束時,會顯示一個計數,顯示找到了多少個唯一字符。儘管是大寫還是不是大寫,但所有內容都被轉換爲小寫。他們的關鍵是使用集合。這是我到目前爲止。儘管事實上我使用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