The function is: replace zhangsan
, lisi
, in wangwu
the target string with the string , ; the result is: ; 1. The method used ;names=[\"#1\",\"#2\",\"#3\"]
#1
#2
#3
names=[\"zhangsan\",\"lisi\",\"wangwu\"]
std::string
replace
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. Use std::string
the find
sum substr
method to splice to generate a new string;
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;
Replace vector<string>
the in item
the target array with the#1;#2...
std::string m_data = "asdfasdf:#0;fasdfsd:#1;fasdfsdf:#2---------";
std::vector<std::string> replace_str;
replace_str.push_back("zhangsan");
replace_str.push_back("lisi");
replace_str.push_back("wangwu");
std::string placeholder = "#";
size_t position_begin = 0;
std::string result_new;
for (auto item = replace_str.begin(); item != replace_str.end(); ++item) {
std::string placeholder_tmp = placeholder + std::to_string(item - replace_str.begin());
size_t found = m_data.find(placeholder_tmp);
if (found != std::string::npos) {
result_new.append(m_data.substr(position_begin, found - position_begin));
result_new.append(*item);
position_begin = found + placeholder_tmp.size();
}
}
result_new.append(m_data.substr(position_begin));
The result is:
when processing json
the format, to json
put the structure string under the string node, it is necessary to add a shift character to the front json
of the original string ;"
\\
string org(buf);
string result;
size_t begin = 0;
size_t pos = org.find("\"");
while (pos != std::string::npos) {
result.append(org.substr(begin, pos - begin)).append("\\");
begin = pos;
pos = org.find("\"", begin + 1);
}
result.append(org.substr(begin, pos - begin));
3. Use sprintf
the function to %s
generate a new string;
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;