Testing for repeated characters in a string

后端 未结 11 696
闹比i
闹比i 2020-12-16 22:55

I\'m doing some work with strings, and I have a scenario where I need to determine if a string (usually a small one < 10 characters) contains repeated characters.

11条回答
  •  时光说笑
    2020-12-16 23:36

    Since you're using 3.5, you could do this in one LINQ query:

    var results = stringInput
      .ToCharArray() // not actually needed, I've left it here to show what's actually happening
      .GroupBy(c=>c)
      .Where(g=>g.Count()>1)
      .Select(g=>new {Letter=g.First(),Count=g.Count()})
    ;
    

    For each character that appears more than once in the input, this will give you the character and the count of occurances.

提交回复
热议问题