Determine if all characters in a string are the same

ぐ巨炮叔叔 提交于 2019-11-29 17:00:57

问题


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?


回答1:


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




回答2:


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.




回答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.




回答4:


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




回答5:


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

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



回答6:


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.



来源:https://stackoverflow.com/questions/16027475/determine-if-all-characters-in-a-string-are-the-same

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!