如何用双C 替换字符串的一部分

how to replace part of a string with a double c++

本文关键字:一部分 字符串 替换 何用双      更新时间:2023-10-16

我一直在堆栈溢出和网络上搜索,似乎找不到我问题的答案。

如何用变量

替换字符串的一部分

示例:我想用变量'number'替换此字符串末尾的" #N"。

首次尝试:

string firstline= "will find the answer in Chapter #N.";
firstline.replace(firstline.begin(),firstline,end(),"#N",number);

事实证明,替换函数不允许您将这些函数作为变量传递。

第二次尝试:

我找到了一个用另一个字符串更改字符串的部分的YouTube教程。

string replace_all(string str, const string &from, const string &to)
{
int pos=0;
int flen= from.length();
int tlen = to.length();
while((pos= str.find(from,pos)) != -1)
{
   str.replace(pos,flen,to);
   pos += tlen;
}
return str;
}
int main()
{
char str[] = "will find the answer in Chapter #N."
cout<< replace_all(str, "we", "you"); 
return 0;
}

进行了一些更改,以使第三参数成为双重,但是我仍然无法使用它。

任何帮助让我获得正确答案的帮助将不胜感激。

编辑: @sneha提出了我使用to_string()

将变量更改为字符串的建议

我做了这个建议,我的代码现在可以编译,但是我无法成功更改字符串。输出仍然是"will find the answer in Chapter #N."

int main()
{
double number =20;
char str[] = "will find the answer in Chapter #N."
cout<< replace_all(str, "we", to_string(number)); 
return 0;
}
string replace_all(string str, const string &from, const string &to)
{
int pos=0;
int flen= from.length();
int tlen = to.length();
while((pos= str.find(from,pos)) != -1)
{
   str.replace(pos,flen,to);
   pos += tlen;
}
return str;
}

使用

将双重变量更改为字符串
    std::to_string(c1)

然后将字符串替换为

编辑:

string replace_all(string str, const string &from, const string &to) {
int flen= from.length();
auto val = str.find("#N");
if (val != string::npos) str.replace(val, flen, to);
return str;
}

这里的npos意味着找不到位置 - 未找到字符串。希望这会有所帮助。

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
    string firstline= "will find the answer in Chapter #N.";
    if(firstline.find("#N") != string::npos)
        firstline.replace(firstline.find("#N"), string("#N").size(), to_string(5));
    cout<<firstline<<endl;
    // will find the answer in Chapter 5.
    return 0;
}
#include <iostream>
#include <string>
using namespace std;
void Replace(string& s, double v) {
    auto it = s.find("#N");
    if (it != string::npos) s.replace(it, 2, to_string(v));
}
int main() {
    string firstline = "will find the answer in Chapter #N.";
    Replace(firstline, 12.35);
    cout << firstline << endl;
    return 0;
}