如何在C++中实现Python的.startswith()与in关键字等效功能
C++ 实现startswith与in关键字等效功能说明
原有代码错误原因
你编写的代码报错核心是类型不匹配:n[0] 是char类型的单个字符,而"J"是C风格字符串字面量,类型为const char*,二者比较实际是在对比内存地址而非字符值,自然无法得到预期结果。如果仅判断单个字符开头,把"J"改成单引号包裹的'J'即可临时解决,但这种方案不支持多字符前缀判断,不是最优解。
最优实现方案
1. 等效Python str.startswith() 功能
C++20及以上版本
标准库已经内置了对应方法,直接调用即可,支持任意长度的前缀判断:
#include <iostream> #include <vector> #include <string> using namespace std; int main() { vector<string> names {"John","Mary","Joanne","David"}; for (const auto& n : names) { // 用const引用避免拷贝,效率更高 if (n.starts_with("J")) { cout << n << endl; } } return 0; }
C++11/14/17版本
没有内置starts_with方法,可以自行封装通用工具函数:
#include <iostream> #include <vector> #include <string> using namespace std; bool starts_with(const string& str, const string& prefix) { if (str.length() < prefix.length()) return false; return str.compare(0, prefix.length(), prefix) == 0; } int main() { vector<string> names {"John","Mary","Joanne","David"}; for (const auto& n : names) { if (starts_with(n, "J")) { cout << n << endl; } } return 0; }
2. 等效Python in 关键字(判断字符/子串是否存在)
直接调用std::string的find方法即可:如果找不到目标,会返回string::npos特殊常量,判断返回值不等于该常量即代表存在:
#include <iostream> #include <vector> #include <string> using namespace std; int main() { vector<string> names {"John","Mary","Joanne","David"}; for (const auto& n : names) { // 判断单个字符存在,对应Python的 'J' in n if (n.find('J') != string::npos) { cout << n << endl; } // 判断多字符子串存在可直接传字符串,例如判断"oh"是否存在: // if (n.find("oh") != string::npos) } return 0; }
内容的提问来源于stack exchange,提问作者Louloumonkey
相关产品推荐
相关产品推荐

