how to check string start in C++

2020-01-26 06: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.startswith(smallString);

标签: c++ string
12条回答
Emotional °昔
2楼-- · 2020-01-26 06:44

I'm surprised no one has posted this method yet:

#include <string>    
using namespace std;

bool starts_with(const string& smaller_string, const string& bigger_string) 
{
    return (smaller_string == bigger_string.substr(0,smaller_string.length()));
}
查看更多
霸刀☆藐视天下
3楼-- · 2020-01-26 06:49

The correct solution, as always, comes from Boost: boost::algorithm::starts_with.

查看更多
戒情不戒烟
4楼-- · 2020-01-26 06:49

With C++20 you can use std::basic_string::starts_with (or std::basic_string_view::starts_with):

#include <string_view>

std::string_view bigString_v("Winter is gone"); // std::string_view avoids the copy in substr below.
std::string_view smallString_v("Winter");
if (bigString_v.starts_with(smallString_v))
{
    std::cout << "Westeros" << bigString_v.substr(smallString_v.size());
}
查看更多
Fickle 薄情
5楼-- · 2020-01-26 06:50

To optimize a little bit:

if ( smallString.size() <= bigString.size() &&
     strncmp( smallString.c_str(), bigString.c_str(), smallString.length() ) == 0 )

Don't forget to #include <cstring> or #include <string.h>

查看更多
甜甜的少女心
6楼-- · 2020-01-26 06:52

Either create a substring that is the length of your smallString variable, and compare the two. Or do a search for the substring smallString and see if it returns index 0

查看更多
淡お忘
7楼-- · 2020-01-26 06:55

http://www.cplusplus.com/reference/string/string/substr/

You can use string.substr() to see any number of characters from any position, or you could use a string.find() member.

查看更多
登录 后发表回答