Determine if all characters in a string are the sa

2019-02-08 17:05发布

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?

6条回答
何必那么认真
2楼-- · 2019-02-08 17:26
char[] chrAry = inputStr.ToCharArray();
char first = chrAry[0];

var recordSet = from p in chrAry where p != first select p;
return !recordSet.Any();
查看更多
相关推荐>>
3楼-- · 2019-02-08 17:27

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

查看更多
走好不送
4楼-- · 2019-02-08 17:30

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.

查看更多
The star\"
5楼-- · 2019-02-08 17:30

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.

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-02-08 17:32

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.

查看更多
Fickle 薄情
7楼-- · 2019-02-08 17:37

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

查看更多
登录 后发表回答