Check if one string is a prefix of another

前端 未结 13 871
-上瘾入骨i
-上瘾入骨i 2020-12-08 04:21

I have two strings which I\'d like to compare: String and String:. Is there a library function that would return true when passed these two strings

13条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 04:25

    How about simply:

    bool prefix(const std::string& a, const std::string& b) {
      if (a.size() > b.size()) {
        return a.substr(0,b.size()) == b;
      }
      else {
        return b.substr(0,a.size()) == a;
      }
    }
    

    C++ not C, safe, simple, efficient.

    Tested with:

    #include 
    #include 
    
    bool prefix(const std::string& a, const std::string& b);
    
    int main() {
      const std::string t1 = "test";
      const std::string t2 = "testing";
      const std::string t3 = "hello";
      const std::string t4 = "hello world";
      std::cout << prefix(t1,t2) << "," << prefix(t2,t1) << std::endl;
      std::cout << prefix(t3,t4) << "," << prefix(t4,t3) << std::endl;
      std::cout << prefix(t1,t4) << "," << prefix(t4,t1) << std::endl;
      std::cout << prefix(t1,t3) << "," << prefix(t3,t1) << std::endl;
    
    }
    

提交回复
热议问题