How to check if a string starts with a substring from a vector of substrings in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>

// Function to check if a string starts with another string
bool startsWith(const std::string& string, const std::string& prefix) {
    return string.rfind(prefix, 0) == 0;
}

// Function to check if the string starts with any substring from the vector
bool startsWithAny(const std::string& string, const std::vector<std::string>& substrings) {
    for (const auto& substring : substrings) {
        if (startsWith(string, substring)) {
            return true;
        }
    }
    
    return false;
}

int main() {
    std::string str = "abcdefg";
    
    std::vector<std::string> substrings = {"xy", "poq", "mnop", "abc", "rsuvw"};

    // Check if the string starts with any substring from the vctor
    if (startsWithAny(str, substrings)) {
        std::cout << "The string starts with a substring from the vector." << std::endl;
    } else {
        std::cout << "The string does not start with any substring from the vector." << std::endl;
    }

    return 0;
}


/*
run:

The string starts with a substring from the vector.

*/

 



answered Apr 3 by avibootz
...