Determine if all characters in a string match

I have a situation where I need to try to filter out fake SSNs. From what I have seen so far, if they are fake, they have the same number or 123456789. I can filter the latter, but is there an easy way to determine if all the characters are the same?

+7
source share
6 answers

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

+38
source

This method should do the trick:

public static bool AreAllCharactersSame(string s)
{
    return s.Length == 0 || s.All(ch => ch == s[0]);
}

Explanation: if the string length is 0, then, of course, all characters are the same. Otherwise, the string characters are the same if they are all equal to the first.

+5
source

To get rid of this problem as we are talking about SSN. You can check and use this CodeProject demo project to verify SSN. Although it is in VB.Net, I think you can come up with the same idea.

+3
source

Grab the first character and loop.

var ssn = "222222222";
var fc = ssn[0];

for(int i=0; i<ssn.Length; i++)
{
    if(ssn[i]!=fc)
        return false;
}

return true;

of course you should also check the length ssn

+1
source
char[] chrAry = inputStr.ToCharArray();
char first = chrAry[0];

var recordSet = from p in chrAry where p != first select p;
return !recordSet.Any();
+1
source

What do you think about it:

"jhfbgsdjkhgkldhfbhsdfjkgh".Distinct().Skip(1).Any()

To not count the number of characters? you must check to zero or empty.

-1
source

All Articles