小智 9
template<class C, class T, class A>
bool starts_with(std::basic_string<C,T,A> const& haystack,
std::basic_string<C,T,A> const& needle)
{
return needle.length() <= haystack.length() &&
std::equal(needle.begin(), needle.end(), haystack.begin());
}
Run Code Online (Sandbox Code Playgroud)
请注意,长度检查不是过早优化,需要满足std :: equal的前提条件.
小智 5
std::string full = "AAB", pre= "AA";
bool prefixed = full.find( pre ) == 0;
Run Code Online (Sandbox Code Playgroud)
或者呢:
bool prefixed = full.compare( 0, pre.size(), pre ) == 0;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4800 次 |
| 最近记录: |