返回题解分享
讨论 / 题解分享/ 帖子详情

替换单词 - 题解

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str;
    getline(cin , str);
    //str.find("black") 返回 "black" 的起始位置
    //如果返回 npos,表示没有找到目标子字符串,
    //直接调用 replace 会导致未定义行为
    size_t pos = 0;//参数 pos 指定了从哪个位置开始查找。
    while ( (pos = str.find("black"),pos) != string::npos ) {
        str.replace(str.find("black") , 5 , "block");
    } 
    cout << str << endl;
    return 0;
}
0 回复 0 转发 0 喜欢 6 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!