這是一個問題:迭代通過串並計數出現
- 編寫一個程序,按字母順序從控制檯打印讀取字符串從輸入字符串中的所有字母和多少次他們中的每一個發生在字符串中。
起初它似乎很有趣,並不太複雜,但我無法解決它。
public static void Letters()
{
string input;
Console.Write("Enter a string: ");
input = Console.ReadLine();
var chars = new List<char>();
//To populate characters with the letters of the input but without repetition
for(int index = 0; index < input.Length; index++)
{
if(!characters.Contains(input[index]))
characters.Add(input[index]);
}
//To increment the counter corresponding to the character index
int[] counter = new int[characters.Count];
//Now what ?!
}
我的想法是:
我創建一個集合容納輸入字符串中的字母,沒有任何重複。
然後,我使用一個相同大小的int數組,以便每個int都保存輸入字符串中相應字母出現的次數。
我不僅不知道如何實現這一點,但我有一種感覺,它不是一個理想的解決方案 的問題。可能有一個查詢或lambda表達式可以使這個簡單的 實現和閱讀。
注意:接下來的問題具有相同的性質。不同的是,它要求 用單個「aaabbbccc」替換爲「abc」的重複字母。
如果描述邏輯,我將不勝感激。我會嘗試自己實現它, 只是指向我的邏輯。
編輯:
這是我的答案使用字典
public static void Letters()
{
string input;
Console.Write("Enter a string: ");
input = Console.ReadLine();
var dict = new Dictionary<char, int>();
for(int index = 0; index < input.Length; index++)
{
char theKey = input[index]; //just for clarity
if(!dict.ContainsKey(theKey))
dict.Add(theKey, 1);
else
dict[input[index]]++;
}
foreach(var key in dict.Keys)
{
Console.WriteLine("{0}\t{1}", key, dict[key]);
}
這是作業嗎? – matcheek
在哪個公司面試中你被要求寫這個程序? –
不是它不是一個家庭作業,也不是一個採訪,它是在這個真棒網站「www.introprogramming.info/english-intro-csharp-book/read-online/chapter-13-strings-and-text-processing/#_Toc362296495 」。該網站的設計有點雜亂,但它的練習是像我這樣的初學者非常好:)。這個特殊的問題是數字22 – Mustafa