23

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?

RBT
  • 24,161
  • 21
  • 159
  • 240
Jhorra
  • 6,233
  • 21
  • 69
  • 123
  • 1
    s != null && s.Length > 1 && s[s.Length - 1] == s[0] – Jay Apr 16 '13 at 01:54
  • Just use the first character in the string and use the answers to this previous question to count the number of occurances: http://stackoverflow.com/questions/10391481/number-of-occurrences-of-a-character-in-a-string – JeffO Apr 16 '13 at 01:55
  • How many times will the problem be in other places? If needed offset by uncertainty required... – Jay Apr 16 '13 at 03:27

6 Answers6

58

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

AShelly
  • 34,686
  • 15
  • 91
  • 152
10

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.

Adam Mihalcin
  • 14,242
  • 4
  • 36
  • 52
3

To get rid of this problem, since we are talking about SSN. You can check and use this CodeProject demo project to validate SSN. Though this is in VB.Net, I guess you can come up with the same idea.

RBT
  • 24,161
  • 21
  • 159
  • 240
roybalderama
  • 1,650
  • 21
  • 38
  • Coding up the restrictions here is probably a better solution than any filter you think up. – AShelly Apr 16 '13 at 02:06
  • but how would you validate an SSN if values entered were the fake one? for example 123456798? There are number of rules that we need to implement with our validation. Checking if all characters are the same wouldn't suffice to make it reliable. – roybalderama Apr 16 '13 at 02:11
  • I wasn't clear. I meant that to OP's problem would be best solved by implementing all the rules in the project linked here, rather than creating a few simple filters similar to the one they proposed in the question. – AShelly Sep 30 '22 at 02:38
1

Grab 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 length of ssn

Niyoko
  • 7,512
  • 4
  • 32
  • 59
1
char[] chrAry = inputStr.ToCharArray();
char first = chrAry[0];

var recordSet = from p in chrAry where p != first select p;
return !recordSet.Any();
Damon Ford
  • 21
  • 3
-1

What do you think about that:

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

To avoid counting the whole number of character? you are supposed to check before null or empty.

Yann
  • 11
  • 3