Function to determine whether std::string ends with a specific character

Asked 1 years ago, Updated 1 years ago, 114 views

In Python, string.endwith could be inspected.

Does C++ also have a function that determines whether std::string ends with a specific character or not?

c++ stdstring

2022-09-22 15:58

1 Answers

C++ has the ability to compare strings themselves, but it doesn't have a function that tells you if they end with a specific string. So you have to do it yourself.

#include <iostream>

/*Function that checks if fillString ends with ending*/
bool hasEnding (std::string const &fullString, std::string const &ending) {
    if (fullString.length() >= ending.length()) {
        return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending)); //Check if the fullString is the same from the length minus the length of the ending
    } If the length of the ending is longer than the length of the else { //fullString -> Always False
        return false;
    }
}

int main () {
    std::string test1 = "binary";
    std::string test2 = "unary";
    std::string test3 = "tertiary";
    std::string test4 = "ry";
    std::string ending = "nary";

    std::cout << hasEnding (test1, ending) << std::endl;
    std::cout << hasEnding (test2, ending) << std::endl;
    std::cout << hasEnding (test3, ending) << std::endl;
    std::cout << hasEnding (test4, ending) << std::endl;

    return 0;
}


2022-09-22 15:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.