0
点赞
收藏
分享

微信扫一扫

C++笔记-使用指定字符串替换目标字符串中的字串

独兜曲 2022-02-17 阅读 128
c++

功能是:用字符串zhangsanlisiwangwu替换目标字符串names=[\"#1\",\"#2\",\"#3\"]中的#1#2#3
结果是:names=[\"zhangsan\",\"lisi\",\"wangwu\"]
1.使用std::stringreplace方法;

std::string org_str = "names=[\"#1\",\"#2\",\"#3\"]";
std::string str_0 = "zhangsan";
std::string str_1 = "lisi";
std::string str_2 = "wangwu";
size_t pos_0 = org_str.find("#1");
size_t pos_1 = org_str.find("#2");
size_t pos_2 = org_str.find("#3");
org_str.replace(org_str.begin() + pos_2, org_str.begin() + pos_2 + 2, str_2);
org_str.replace(org_str.begin() + pos_1, org_str.begin() + pos_1 + 2, str_1);
org_str.replace(org_str.begin() + pos_0, org_str.begin() + pos_0 + 2, str_0);

2.使用std::stringfindsubstr方法,拼接生成新的字符串;

std::string org_str = "names=[\"#1\",\"#2\",\"#3\"]";
std::string str_0 = "zhangsan";
std::string str_1 = "lisi";
std::string str_2 = "wangwu";

size_t pos_0 = org_str.find("#1");
size_t pos_1 = org_str.find("#2");
size_t pos_2 = org_str.find("#3");
org_str = org_str.substr(0, pos_0) + str_0 + org_str.substr(pos_0 + 2, pos_1 - pos_0 - 2)
+ str_1 + org_str.substr(pos_1 + 2, pos_2 - pos_1 - 2)
+ str_2 + org_str.substr(pos_2 + 2);
cout << org_str.c_str() << endl;

3.使用sprintf函数的%s生成新的字符串;

std::string org_str = "names=[\"%s\",\"%s\",\"%s\"]";
std::string str_0 = "zhangsan";
std::string str_1 = "lisi";
std::string str_2 = "wangwu";
char* pbuf = new char[org_str.size() + str_0.size() + str_1.size() + str_2.size()]{ 0 };
sprintf(pbuf, org_str.c_str(), str_0.c_str(), str_1.c_str(), str_2.c_str());
org_str = pbuf;
delete[] pbuf;
举报

相关推荐

0 条评论