C++字符串子串替换代码结果不符预期,求原因解析
问题原因分析与修正
咱们直接戳破问题核心:你调用string::replace时,第二个参数传错了!
string::replace(pos, len, new_str)的作用是:从字符串的pos位置开始,删除len个字符,再把new_str插入到这个位置。
你要替换的目标子串是"they",它的长度是4,不是你写的2。现在你传了2,意思是只删除"they"的前2个字符(t和h),然后把s4插进去。原字符串里剩下的"ey"还留在原位,这就导致最终结果和你的预期完全不符。
修正后的代码
#include <iostream> #include <string> using namespace std; int main() { string s3("There they go again!"), s4("Bob and Bill"); string target = "they"; size_t pos = s3.find(target); // 建议用size_t,匹配find返回的类型 if (pos != string::npos) { s3.replace(pos, target.length(), s4); // 用目标子串的实际长度作为第二个参数 } cout << s3 << endl; cout << s4 << endl; return 0; }
额外小提示
- 别用
int接收find的返回值:string::find返回的是size_t(无符号整数类型),如果用int接收,当找不到子串返回string::npos(本质是size_t的最大值)时,会出现溢出问题,用size_t更安全。 - 手动数子串长度容易出错:直接调用
target.length()或target.size()获取长度,既准确又省心。
内容的提问来源于stack exchange,提问作者kkxx
相关产品推荐
相关产品推荐

