Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,988 questions

51,933 answers

573 users

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, 2025 by avibootz
...