C++判断字符串是否包含子串的代码运行报错如何解决?
问题原因
- 核心编译错误:你定义的结构体中
string1、string2是C风格char数组,不属于C++标准库的std::string类型,char数组没有内置的find成员方法,调用strings.string1.find()会直接触发编译报错,这就是你运行报错的根源。 - 额外逻辑缺陷:
equalCheck函数的循环条件使用了||运算符,只要两个字符串有一个未到末尾就继续循环,如果两个字符串长度不一致,会访问短字符串结束符\0之后的越界内存,可能导致异常输出或程序崩溃。
解决办法
方案1(推荐):改用std::string类型处理字符串
该方案适配你原本想用的find方法,无需手动处理字符串底层逻辑,代码更简洁安全:
- 引入
<string>头文件,对应std::string类型的依赖 - 将结构体中的char数组替换为
std::string类型 - 可直接用
==运算符判断字符串相等,替换手写的循环判断逻辑
修改后的完整代码示例:
#include <iostream> #include <string> using namespace std; //Struct to store information struct strings { string string1, string2; } strings; //Function to check if the strings are equal void equalCheck(){ if (strings.string1 == strings.string2) { cout << "The strings are equal" << endl; } else { cout << "The strings are not equal" << endl; } } //Function to check for a substring void substringCheck(){ if (strings.string1.find(strings.string2) != string::npos) { cout << "found!" << '\n'; } else { cout << "not found!" << '\n'; } } int main() { //Ask the user for two strings cout << "Please type the first string: "; cin >> strings.string1; cout << "Please type the second string: "; cin >> strings.string2; equalCheck(); substringCheck(); return 0; }
方案2:保留C风格char数组,用C标准库函数处理
如果坚持使用char数组,需要引入<cstring>头文件,调用C标准库的字符串处理函数:
- 用
strcmp函数判断两个字符串是否相等,替换手写的循环逻辑 - 用
strstr函数判断子串存在性,替换不存在的find方法调用
修改后的核心函数示例:
#include <cstring> // 相等判断函数 void equalCheck(){ if (strcmp(strings.string1, strings.string2) == 0) { cout << "The strings are equal" << endl; } else { cout << "The strings are not equal" << endl; } } // 子串判断函数 void substringCheck(){ if (strstr(strings.string1, strings.string2) != NULL) { cout << "found!" << '\n'; } else { cout << "not found!" << '\n'; } }
内容的提问来源于stack exchange,提问作者user16003119
相关产品推荐
相关产品推荐

