检查字符串是否以另一个字符串开头:find或compare
check if string starts with another string: find or compare?
如果你想知道一个字符串是否以另一个字符串开头,你如何在c++/STL中做到这一点?在Java中有String.startsWith
, Python也有string.startwith
, STL没有直接的方法。取而代之的是std::string::find
和std::string::compare
。到目前为止,我使用了这两种方法,主要取决于我当前的心情:
if ( str1.compare( 0, str2.length(), str2 ) == 0 )
do_something();
if ( str1.find(str2) == 0 )
do_something();
当然,你也可以做str.substr(0,str2.length()) == str2
,也许还有一些其他的方法可以达到同样的效果。find
比compare
更方便,但我看到更多的人推荐compare
而不是find
。
但是哪一个是首选呢?是否存在性能差异?它是否依赖于实现(GCC, vc++等)?
find
的缺点是,如果str1
很长,那么它将毫无意义地搜索str2
。我从来没有注意到一个优化器足够聪明,可以意识到你只关心结果是否为0,并在str1
开始后停止搜索。
compare
的缺点是您需要检查str2.length()
是否大于str1.length()
(或者捕获产生的异常并将其视为错误结果)。
令人失望的是,在标准库中最接近您想要的是std::strncmp
(当然您需要使用c_str()
),因此需要boost::starts_with
或您自己的等同物,其中包括边界检查。
boost有一个算法starts_with
可以相当有效地实现它:http://www.boost.org/doc/libs/1_41_0/doc/html/boost/algorithm/starts_with.html
没有关于STL实现必须如何实现查找或比较的要求,除了标准的东西(返回值…),所以它完全依赖于实现。
由于find()
可能无论如何都必须搜索整个string
,如果您愿意,可以像这样包装compare()
:
#include <iostream>
#include <string>
using namespace std;
bool starts_with(const string& s1, const string& s2) {
return s2.size() <= s1.size() && s1.compare(0, s2.size(), s2) == 0;
}
int main() {
const string s("zipzambam");
cout << starts_with(s, "zip") << endl;
}
find
可能不得不搜索整个字符串寻找匹配,即使第一个字符不匹配,所以我建议compare
,或者正如@Foo Bah所提到的,你可以使用boost的starts_with
算法。
你可以试试std::mismatch
,这个算法唯一的愚蠢的的事情是你必须确保第一个范围小于或等于第二个范围
- 无法使用substr和find正确解析带有空格的字符串
- 字符串::find在c++中使用了哪种算法
- std::string::find 为取消引用的迭代器和等效字符串文本返回不同的值
- 如何使用 std::find 从向量的第一个元素中查找字符串<字符串对<字符串、字符串> >类型?
- 在无序映射<字符串上使用 find(),向量<string>>与 C++ 中的有序映射花费相同的时间
- 使用 std::string::find 在一个小字符串中查找较长的字符串
- C++ 字符串迭代器"find first of"
- 使用 string::find 和 string::substr 拆分字符串的函数返回错误的标记
- 表演查找子字符串.substr与find
- 查找空字符串时的find与find_first_of
- 字符串::find(charc)应该在c++中返回什么
- 是否可以使用字符串::find来检测换行符
- 为什么s.find在失败时返回字符串::npos而不是s.length()
- 使用字符串进行递归::find()
- C-使用find()分解字符串
- 在字符串 c++(无子字符串)上使用 str.find() 时执行操作
- 我的字符串::find()在这里做什么
- cpp字符串find()无法按预期工作-返回大垃圾值
- 使用字符串::find搜索不同的单词.对诸如“;是;
- 如何将排序函数应用于字符串.find( ) 以按字母顺序打印结果