How to check whether a string starts with another string in C++?
Posted on In Programming, QA, TutorialHow to check whether a string starts with another string in C++? For example,
startwith("big string here...", "big") --> True
and
startwith("big string here...", "small") --> False
and
startwith("big", "big string here") --> False
The std::string::compare()
standard library function of C++ can be used.
int compare( size_type pos1, size_type count1,
const basic_string& str ) const;
For check whether a string starts wit another string, call the compare()
function from the string with str
as the “another string”, pos1
can be set to 0, count1
to be str
‘s length.
Here is one example.
#include <iostream>
#include <string>
bool startswith(const std::string& str, const std::string& cmp)
{
return str.compare(0, cmp.length(), cmp) == 0;
}
int main ()
{
std::cout << startswith("big string here...", "big") << std::endl;
std::cout << startswith("big string here...", "small") << std::endl;
std::cout << startswith("big", "big string here") << std::endl;
return 0;
}