题解 | #单词替换#

单词替换

http://www.nowcoder.com/practice/5b58a04679d5419caf62c2b238e5c9c7

善用c++ string的erase() insert(),同时要注意遍历的时候经过替换之后原字符串就变了,就得重新调整索引下标i。


#include<bits/stdc++.h>
using namespace std;
int main(){
    string str, a, b;
    while(getline(cin, str)){
        if(str == "")break;
        cin >> a >> b;
        //查找字符串
        int i = 0;
        while(i < str.size()){
            if(i == 0 || str[i-1] == ' '){//每个单词的首字母处
                int j = 0;
                for(; j < a.size() && str[i+j] != ' '; j++){
                    if(str[i+j] != a[j])break;//当前单词不匹配
                }
                if(j < a.size() || str[i+j] != ' '){i++; continue;}//长度不一致,不匹配
                //单词匹配,替换
                str.erase(i, a.size());
                str.insert(i, b);
                i = i + b.size();
            }
            i++;
        }
        cout << str << endl;
    }
    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务