Determine if all characters in a string are the same

我们两清 提交于 2019-11-30 11:41:36

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

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.

lexeRoy

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.

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

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

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

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.

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