How to efficiently check if a word's all letters are the same in C++

I have checked and couldn't a better option by checking the word's letters one by one. I've decided to use the ascii equivalence of the letter check by diving the word but didn't lead to any where as well. Any Ideas?

Answers


#include <string>

bool are_all_characters_the_same(const std::string &s) {
    return (s.size() == 0) || s.find_first_not_of(s[0]) == std::string::npos;
}

Clearly in the worst case it can't be done without examining every character. Whichever character(s) you don't examine, might be the same as the others or different, and the result needs to be sensitive to that in the case where the ones you do examine are all the same.

If you know something about what might be in the string, then the order in which you examine the characters might affect how early you can bail out. But knowing nothing, you may as well read them in order, and reading them in order might result in better cache performance.

Things get more complicated if the string is long enough that it's worth parallelizing.


Need Your Help

How to truncate the Icon name with Xcode?

ios xcode icons assets

There are several schemes in my project, for each scheme there is an Icon image file in the Images.xcassets folder, like this:

How to display string value in Toast Message Box?

java android

I am new to Android Environment.I have to display Toast message box using the String[] value.But the Toast message Syntax cannot accept the String[] value.How can i display message the String[] val...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.