如何用双C 替换字符串的一部分
how to replace part of a string with a double c++
我一直在堆栈溢出和网络上搜索,似乎找不到我问题的答案。
如何用变量
替换字符串的一部分示例:我想用变量'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;
}
相关文章:
- C++:如何使函数只返回作为列表一部分的字符串
- 如何将字符串的一部分转换为整数
- 如何有效地将一个大std::字符串的一部分转换为float
- 需要从字符串数组的一部分访问元素
- 当 NUL 字符被定义为字符串的一部分时,为什么 strlen() 不计算终止 NUL 字符的字节?
- 如何正确实现 std::all_of 函数来验证字符串的一部分?
- boost::async_write 跳过字符串的一部分
- 如何在不复制的情况下比较字符串的一部分?
- 我如何在QT中获得字符串的一部分
- 如何在C++中比较数组中字符串的一部分的字符串
- 如何在 c++ 中拆分字符串的一部分
- 字符数组仅占用字符串的一部分
- 如何用双C 替换字符串的一部分
- 如何在字符串中选择句子的一部分 (C++)
- 如何拆分 QString 并将一部分字符串保存在浮点数的向量中
- 为什么C 正则只能找到JavaScript Regex在字符串中找到的一部分
- 字符串操纵和忽略字符串的一部分
- 在C 中更新字符串的一部分
- 有条件地确定字符串是否是数组的一部分
- 尝试在 Cocos2d-X C++中设置一个带有整数作为其字符串一部分的 CCLabelTTF