Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if all characters in a string are the same

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?

like image 457
Jhorra Avatar asked Apr 16 '13 01:04

Jhorra


People also ask

How do I check if a string has duplicates?

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.

How do you check if letters are in a string?

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.


2 Answers

return (ssn.Distinct().Count() == 1)

like image 104
AShelly Avatar answered Sep 20 '22 12:09

AShelly


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.

like image 31
Adam Mihalcin Avatar answered Sep 20 '22 12:09

Adam Mihalcin