Reads in several strings and prints only those ending in "r" or "ay". - C++ STL

C++ examples for STL:string

Description

Reads in several strings and prints only those ending in "r" or "ay".

Demo Code

#include <iostream>
#include <string>

bool validate(const std::string&);

int main(int argc, const char* argv[]) {
    std::string string1 = "this is a test";
    std::string string2 = "test test test test";
    std::string string3 = "What is the date today";
    std::string string4 = "hi hi hi hi hi";

    std::cout << (validate(string1) ? string1 + "\n" : "");
    std::cout << (validate(string2) ? string2 + "\n" : "");
    std::cout << (validate(string3) ? string3 + "\n" : "");
    std::cout << (validate(string4) ? string4 + "\n" : "");

    return 0;// w  w w .java2  s.c  om
}
// tests whether given string ends in "r" or "ay"
bool validate(const std::string& base) {
    return ((base.substr(base.length() - 2) == "ay") ||
            (base.substr(base.length() - 1) == "r"));
}

Result


Related Tutorials