For example,
true if the string contains one or more repeated characters.
false if the string is composed of all different characters.
"A normal string with repeated characters" --> true
"Another" --> false
"abcdefghijklm" --> false
"aa" --> true
Think of the string as a sequence of characters. A sequence contain at least one duplicate if the count of the distinct elements is not equal to the overall count of the elements.
In other words:
bool containsDuplicates = str.Distinct().Count() != str.Length;
(This will be constructing a HashSet<char>
behind the scenes, so it's basically equivalent to the answers which construct one explicitly and then use the Count
property... I just find this approach slightly clearer, personally, with the explicit mention of distinctness.)
See more on this question at Stackoverflow