Testing for repeated characters in a string

后端 未结 11 830
闹比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:34

    When there is no order to work on you could use a dictionary to keep the counts:

    String input = "AABCD";
    var result = new Dictionary(26);
    var chars = input.ToCharArray();
    foreach (var c in chars)
    {
        if (!result.ContainsKey(c))
        {
            result[c] = 0; // initialize the counter in the result
        }
        result[c]++;
    }
    
    foreach (var charCombo in result)
    {
        Console.WriteLine("{0}: {1}",charCombo.Key, charCombo.Value);   
    }
    

提交回复
热议问题