I have a situation where I need to try and filter out fake SSN numbers. From what I've seen so far if they are fake they're all the same number or 123456789. I can filter for the last one, but is there an easy way to determine if all the characters are the same?
To find the duplicate character from the string, we count the occurrence of each character in the string. If count is greater than 1, it implies that a character has a duplicate entry in the string. In above example, the characters highlighted in green are duplicate characters.
The best method to check the character in a String is the indexOf() method. It will return the index of the character present in the String, while contains() method only returns a boolean value indicating the presence or absence of the specified characters.
return (ssn.Distinct().Count() == 1)
This method should do the trick:
public static bool AreAllCharactersSame(string s)
{
return s.Length == 0 || s.All(ch => ch == s[0]);
}
Explanation: if a string's length is 0, then of course all characters are the same. Otherwise, a string's characters are all the same if they are all equal to the first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With