Check if one string is a prefix of another

前端 未结 13 896
-上瘾入骨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:34

    This is both efficient and convenient:

    str.compare(0, pre.size(), pre) == 0
    

    compare is fast because it uses the fast traits::compare method and doesn't have to copy any data.

    Here, it will compare std::min(str.size(), pre.size()) characters but if the characters in the two ranges are equal it also checks the length of pre and returns a non-zero value if pre is longer than this.

    See the documentation at cplusplus.com.

    I've written a test program that uses this code to compare prefixes and strings given on the command line.

提交回复
热议问题