Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function which takes a string input and removes all the characters which occur a certain number of times

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;
}
like image 745
Khayam Khan Avatar asked Nov 23 '25 21:11

Khayam Khan


2 Answers

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)));
}
like image 164
Hans Kilian Avatar answered Nov 25 '25 10:11

Hans Kilian


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;
}
like image 31
Omid Rajabalian Avatar answered Nov 25 '25 09:11

Omid Rajabalian