Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a const char* begins with a specific string? (C++)

I have a const char* variable and I want to check if it begins with a certain string.

For example:

string sentence = "Hello, world!";
string other = "Hello";
const char* c = sentence.c_str();

if(/*"c" begins with "other"*/)
{
    //Do something
}

How can I do this using the if statement?

like image 395
Ben Avatar asked Oct 31 '25 19:10

Ben


1 Answers

To check whether a C string begins with a certain substring, you could use strncmp().

For C++ strings, there is a std::string::compare() overload that accepts offsets and lengths.

like image 186
NPE Avatar answered Nov 02 '25 10:11

NPE