how to check string start in C++

后端 未结 12 2000
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:15

    I'm surprised no one has posted this method yet:

    #include <string>    
    using namespace std;
    
    bool starts_with(const string& smaller_string, const string& bigger_string) 
    {
        return (smaller_string == bigger_string.substr(0,smaller_string.length()));
    }
    
    0 讨论(0)
  • 2020-11-29 04:16

    To optimize a little bit:

    if ( smallString.size() <= bigString.size() &&
         strncmp( smallString.c_str(), bigString.c_str(), smallString.length() ) == 0 )
    

    Don't forget to #include <cstring> or #include <string.h>

    0 讨论(0)
  • 2020-11-29 04:16

    Either create a substring that is the length of your smallString variable, and compare the two. Or do a search for the substring smallString and see if it returns index 0

    0 讨论(0)
  • 2020-11-29 04:17

    strstr() returns a pointer to the first occurrence of a string within a string.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-29 04:21

    The simplest approach would be:

    if ( smallString.size() <= bigString.size()
        && std::equals( smallString.begin(), smallString.end(), bigString.end() )
    

    (This will also work if one of the two, or both, is a vector. Or any other standard container type.)

    0 讨论(0)
提交回复
热议问题