这里有一个单词"angoora“,'a‘和'o’出现了2次,如果用户输入是2,那么输出应该是"ngr”,函数应该删除a和o,因为它在字符串中出现了2次。如果用户输入3,则输出应为"angoora“,因为没有字符出现3次。
我正在这样做,但我认为这不是一个正确的方式,因为它不会引导我走向我的目标,任何帮助都会非常感谢。
public static SortedDictionary<char, int> Count(string stringToCount)
{
SortedDictionary<char, int> characterCount = new SortedDictionary<char, int>();
foreach (var character in stringToCount)
{
int counter = 0;
characterCount.TryGetValue(character, out counter);
characterCount[character] = counter + 1;
}
return characterCount;
}发布于 2018-07-30 20:29:48
您可以使用此函数
static string Fix(string item, int count)
{
var chars = item.ToList().GroupBy(g => g).Select(s => new { Ch = s.Key.ToString(), Count = s.Count() }).Where(w => w.Count < count).ToList();
var characters = string.Join("", item.ToList().Select(s => s.ToString()).Where(wi => chars.Any(a => a.Ch == wi)).ToList());
return characters;
}发布于 2018-07-30 19:50:52
您可以使用LINQs来查找每个字符出现的次数。然后删除你想要的次数。像这样的东西
public static string RemoveCharactersThatOccurNumberOfTimes(string s, int numberOfOccurances)
{
var charactersToBeRemoved = s.GroupBy(c => c).Where(g => g.Count() == numberOfOccurances).Select(g => g.Key);
return String.Join("", s.Where(c => !charactersToBeRemoved.Contains(c)));
}发布于 2018-07-30 20:01:47
您的characterCount SortedDictionary为空。
目前您正在执行以下操作:
public static SortedDictionary<char, int> Count(string stringToCount)
{
// Create a new empty SortedDictionary
SortedDictionary<char, int> characterCount = new SortedDictionary<char, int>();
// Loop through each character in stringToCount and see if SortedDictionary contains a key equal to this character (it doesn't as dictionary is empty).
foreach (var character in stringToCount)
{
int counter = 0;
characterCount.TryGetValue(character, out counter);
characterCount[character] = counter +1;
}
return characterCount;
}你肯定想要这样的东西:
public static SortedDictionary<char, int> Count(string stringToCount)
{
// Create a new empty SortedDictionary (use var keyword if defining variables)
var characterCount = new SortedDictionary<char, int>();
// Loop through each character and add to dictionary
foreach (var character in stringToCount)
{
// If character already in SortedDictionary.
if (characterCount.TryGetValue(character, out int count))
{
// Increment count value.
characterCount[character] = count + 1;
// Above line can also be: ++characterCount[character];
}
// Else, character not already in dictionary.
else
{
// Add character in dictionary and set count to 1.
characterCount.Add(character, 1);
}
}
return characterCount;
}https://stackoverflow.com/questions/51593197
复制相似问题