Compare char in List C#

时间:2015-10-30 21:29:38

标签: c# list dictionary

I wonder If there is any c# functions that checks if the letter exists more then once? In another word, I send a string to a function as parameter to check whether a letter exist more than once or not. For example the string "AABDCK" should return "A". Is there is any way to use dictionary??

4 个答案:

答案 0 :(得分:4)

Is there is any way to use dictionary??

Yes loop through each character in your string and track the number of occurrences of each character in a Dictionary<char, int>.

Dictionary<char, int> counts = new Dictionary<char, int>();
foreach (var ch in myString)
{
    if (counts.ContainsKey(ch))
    {
        counts[ch]++;
    }
    else counts.Add(ch, 1);
} 

Check the dictionary for keys where the value is > 1.

You can also do this with Linq. I'm not in front of a compiler, but it would look something like

List<char> multipleTimes = myString
    .GroupBy(c => c)
    .Select(g => new { Character = g.Key, Count = g.Count() })
    .Where(a => a.Count > 1)
    .Select(a => a.Character)
    .ToList();

答案 1 :(得分:1)

You could do it using linq, look the comments bellow to understand the code, for sample:

public string GetLetterWithMoreOccurrences(string text)
{
   // check if the text was provided
   if (string.IsNullOrEmpty(letter))
      throw new ArgumentException("You must provide a text.", "text");

   // if it is lower than 2 chars, return the first one
   // I'm not sure if it is what you want, but let's consider it.
   if (text.Length <= 2)
      return text[0];

   // find the first letter
   var letter = text.GroupBy(c => c) // group by char
                    .Select(x => { Letter = x.Key, Total = x.Count() }) // in the group, count how many occurrences each letter has
                    .OrderByDescending(x => x.Total) // order by the total by descending
                    .First(); // get the first one

  return letter;
}

and you can check:

var letter = GetLetterWithMoreOccurrences("AABDCK"); 
// should return "A"

Now, if you want all the letter that has more than one occurrences, you could try:

public string GetLetterAllDuplicates(string text)
{
   // check if the text was provided
   if (string.IsNullOrEmpty(letter))
      throw new ArgumentException("You must provide a text.", "text");

   // if it is lower than 2 chars, return the first one
   // I'm not sure if it is what you want, but let's consider it.
   if (text.Length <= 2)
      return text[0];

   // find the first letter
   var letters = text.GroupBy(c => c) // group by char
                     // in the group, count how many occurrences each letter has
                     .Select(x => { Letter = x.Key, Total = x.Count() }) 
                      // get only the occurrences that has more than 1.. (you can change this parameter)
                     .Where(x => Total > 1) 
                     // get it as array
                     .ToArray();

  var result = string.Join(letters, "");

  return result ;
}

And use it:

var text = GetLetterAllDuplicates("AABKCBD");
// should return "AB"

答案 2 :(得分:0)

You can use:

String.IndexOf("A");

It will return the index of the First A Occurence. If it returns -1, then there are not "A" occurrencies.

And here is my LINQ Implementation without using IndexOf:

string x = "AABCDEF";
List<char> repeatedCharacters = new List<char>();
var groupsOfChars = x.GroupBy(stringCharacter => stringCharacter);
groupsOfChars
.ToList()
.ForEach(item => {
    if (item.Count() > 1) repeatedCharacters.Add(item.Key);
});

Or if you don't need the group:

string x = "AABCDEF";
List<char> repeatedCharacters = new List<char>();
x.GroupBy(stringCharacter => stringCharacter)
.ToList()
.ForEach(item => {
    if (item.Count() > 1) repeatedCharacters.Add(item.Key);
});

And then you could check it:

repeatedCharacters.ForEach(item => {
    Console.WriteLine(item.ToString());
});
//Since repeatedCharacters is an array, you can just simply do:
string stringOfRepeatedCharacters = repeatedCharacters.ToString();
//So you can easily convert the values to a String.
//[ 'A', 'B' ] is the result and it can be "AB".

答案 3 :(得分:0)

it seems like bringing more wood into a forest, but it seems that some answers are incomplete or do not do exactly what was requested or are horrible complex:). string input = "AABZFFZDCZZK"; //can handle null and empty string... var rslt = (string.IsNullOrEmpty(input) ? string.Empty : input) .GroupBy(c => c) .Select(gc => gc.Count() > 1 ? gc.Key : (char)0) .Where(c => c != (char)0) .OrderBy(c => c)//optional .Aggregate(string.Empty, (c, n) => c + n) ; The result is: "AFZ" The question was to provide back string with characters that occur multiple times.