If performance matters, write yourself:
public static bool ContainsDuplicateCharacter(this string s, char c) { bool seenFirst = false; for (int i = 0; i < s.Length; i++) { if (s[i] != c) continue; if (seenFirst) return true; seenFirst = true; } return false; }
This way you only make one pass through the contents of the string, and you exit as soon as possible. In the worst case scenario, you visit all the characters only once. In @ dasblinkenlight's answer, you visited all the characters twice, and in @mensi's answer you should count all instances, even if you have two, you can stop the calculation. In addition, using the Count extension method involves using an Enumerable<char> , which will work slower than direct access to characters with specific indices.
Then you can write:
string s = "12121.23.2"; Debug.Assert(s.ContainsDuplicateCharacter('.')); Debug.Assert(s.ContainsDuplicateCharacter('1')); Debug.Assert(s.ContainsDuplicateCharacter('2')); Debug.Assert(!s.ContainsDuplicateCharacter('3')); Debug.Assert(!s.ContainsDuplicateCharacter('Z'));
I also find it better to have a function that accurately explains what you are trying to achieve. However, you can wrap any of the other answers in such a function.
source share