I have a word "angoora" here 'a' and 'o' occurs 2 time if user input is 2 then output should be "ngr" function should remove a and o because it occur 2 times in a string. if user enter 3 then output should be "angoora" because no character occur 3 times.
I am doing this but I think its not a right way because its not leading me towards my goal, any help would be highly appreciated.
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;
}
You can use LINQs GroupBy to find the number of times each character occurs. Then remove the ones that occur the number of times you want. Something like this
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)));
}
You Can use this Function
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With