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.startswith(smallString);
The index() function locates the first occurrence of c (converted to an unsigned char) in the string pointed to by string. The character c can be the NULL character (\0); the ending NULL is included in the search. The string argument to the function must contain a NULL character (\0) marking the end of the string.
In order to test the beginning and ending of a given string in Python, one can use the methods str. startswith() and str. endswith() .
Search for a character in a string - strchr & strrchr The strchr function returns the first occurrence of a character within a string. The strrchr returns the last occurrence of a character within a string. They return a character pointer to the character found, or NULL pointer if the character is not found.
The startsWith() method checks whether a string starts with the specified character(s). Tip: Use the endsWith() method to check whether a string ends with the specified character(s).
std::string s("Hello world"); if (s.find("Hello") == 0) { std::cout << "String starts with Hello\n"; }
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With