how to check string start in C++

后端 未结 12 2038
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:33

    You can do this with string::compare(), which offers various options for comparing all or parts of two strings. This version compares smallString with the appropriate size prefix of bigString (and works correctly if bigString is shorter than smallString):

    bigString.compare(0, smallString.length(), smallString) == 0
    

    I tend to wrap this up in a free function called startsWith(), since otherwise it can look a bit mysterious.

    UPDATE: C++20 is adding new starts_with and ends_with functions, so you will finally be able to write just bigString.starts_with(smallString).

提交回复
热议问题