KnightValor KnightValor - 7 months ago 51
C++ Question

Determine If String Has All Same Character

Is there a function like

that returns true or false as opposed to a position? I do not need the position, but rather whether or not the string contains all of the same char.


You could write your own function:

bool all_chars_same(string testStr) {
    char letter = testStr[0];

    for (int i = 1; i < testStr.length(); i++) {
        if (testStr[i] != letter)
            return false;

    return true;

Or, using the built in find_fist_not_of:

bool all_chars_same(string testStr) {
    return testStr.find_first_not_of(testStr[0]) == string::npos;