C++:查找字符串字串并替换

C++:查找字符串字串并替换

2018-08-28 21:51:16 sunshine芝火 阅读数 3666更多

分类专栏: C++

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/sunshinezhihuo/article/details/82155156

https://zhidao.baidu.com/question/497175897.html


int main(){
 string a;/////指定串,可根据要求替换
 string b;////要查找的串,可根据要求替换
 string c;
 cin>>a>>b>>c;
 int pos;
 pos = a.find(b);////查找指定的串
 while (pos != -1)
 {
  a.replace(pos,b.length(),c);////用新的串替换掉指定的串

  pos = a.find(b);//////继续查找指定的串,直到所有的都找到为止
 }
 cout<<a<<endl;
 return 0;
} 

这里写图片描述

注意,cin是不能读取空格的。

#include<iostream>
#include<string>
using namespace std;

int main() {
    string str;
    string srcSubStr;
    string dstSubStr;
    string out;

    getline(cin, str);
    getline(cin, srcSubStr);
    getline(cin, dstSubStr);

    int pos;
    pos = str.find(srcSubStr);
    while (pos != -1)
    {
        str.replace(pos, srcSubStr.length(), dstSubStr);
        pos = str.find(srcSubStr);
    }

    cout << str;


}
posted @ 2019-11-02 08:37  grj001  阅读(300)  评论(0编辑  收藏  举报