how to check string start in C++

后端 未结 12 2005
Happy的楠姐
Happy的楠姐 2020-11-29 03:31

Is there any way in C++ to check whether a string starts with a certain string (smaller than the original) ? Just like we can do in Java

bigString.startswi         


        
12条回答
  •  遥遥无期
    2020-11-29 04:17

    I thought it makes sense to post a raw solution that doesn't use any library functions...

    // Checks whether `str' starts with `start'
    bool startsWith(const std::string& str, const std::string& start) {
        if (&start == &str) return true; // str and start are the same string
        if (start.length() > str.length()) return false;
        for (size_t i = 0; i < start.length(); ++i) {
            if (start[i] != str[i]) return false;
        }
        return true;
    }
    

    Adding a simple std::tolower we can make this case insensitive

    // Checks whether `str' starts with `start' ignoring case
    bool startsWithIgnoreCase(const std::string& str, const std::string& start) {
        if (&start == &str) return true; // str and start are the same string
        if (start.length() > str.length()) return false;
        for (size_t i = 0; i < start.length(); ++i) {
            if (std::tolower(start[i]) != std::tolower(str[i])) return false;
        }
        return true;
    }
    

提交回复
热议问题