如何在vector<string>元素中正确使用strstr函数?
修复strstr调用的类型不匹配错误
原报错代码:
vector<string> filtered_items; filtered_items.push_back("test"); for (auto index_name : filtered_items) strstr(index_name, "te");
错误原因
strstr是C标准库函数,它的两个参数都要求是const char*类型,但这里传入的第一个参数index_name是std::string对象,类型不匹配,导致编译器找不到对应的重载函数,抛出报错。
修复方案
方案1:使用std::string::c_str()转换为C风格字符串
调用std::string的c_str()方法,获取指向其内部字符数组的const char*指针,满足strstr的参数要求:
vector<string> filtered_items; filtered_items.push_back("test"); for (auto index_name : filtered_items) strstr(index_name.c_str(), "te");
方案2:改用C++原生的std::string::find方法(推荐)
直接使用std::string自带的find成员函数,不需要依赖C库,更符合C++编码习惯,返回值为匹配子串的起始索引(未找到则返回std::string::npos):
#include <string> // 确保包含string头文件 vector<string> filtered_items; filtered_items.push_back("test"); for (auto index_name : filtered_items) index_name.find("te");
扩展:判断是否找到匹配的示例
如果需要判断子串是否存在,可以这样写:
vector<string> filtered_items; filtered_items.push_back("test"); for (auto index_name : filtered_items) { // 方案1的判断方式 if (strstr(index_name.c_str(), "te") != nullptr) { // 子串存在 } // 方案2的判断方式 if (index_name.find("te") != std::string::npos) { // 子串存在 } }
内容的提问来源于stack exchange,提问作者user2813853
相关产品推荐
相关产品推荐

