这是一个问题:迭代通过串并计数出现
- 编写一个程序,按字母顺序从控制台打印读取字符串从输入字符串中的所有字母和多少次他们中的每一个发生在字符串中。
起初它似乎很有趣,并不太复杂,但我无法解决它。
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