如何将百分号 (%) 替换为两个 %?
How can I replace percent sign (%) with two %'s?
我想尝试用两个%%
符号替换char数组中的一个百分号。因为%
符号会导致问题,所以如果我作为输出字符数组进行写入。因此,在不使用字符串的情况下,百分比符号必须替换为两个%%
符号。
// This array causes dump because of '%'
char input[] = "This is a Text with % Charakter";
//Therefore Percent Sign(%) must be replaced with two %%.
您可以使用std::string
来处理必要的内存重新分配,再加上boost
算法来简化一切:
#include <string>
#include <iostream>
#include <boost/algorithm/string.hpp>
int main()
{
std::string input("This is a Text with % Charakter and another % Charakter");
boost::replace_all(input, "%", "%%");
std::cout << input << std::endl;
}
输出:
这是一个带有%%Charakter和另一个%%Charakter的文本
如果不能使用boost
,可以使用std::string::find
和std::string::replace
:编写自己版本的replace_all
template <typename C>
void replace_all(std::basic_string<C>& in,
const C* old_cstring,
const C* new_cstring)
{
std::basic_string<C> old_string(old_cstring);
std::basic_string<C> new_string(new_cstring);
typename std::basic_string<C>::size_type pos = 0;
while((pos = in.find(old_string, pos)) != std::basic_string<C>::npos)
{
in.replace(pos, old_string.size(), new_string);
pos += new_string.size();
}
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- C++获取两个分隔符之间的字符串并替换它
- 删除两个相邻的元素并用矢量中的单个元素替换它们
- 在这种情况下,有没有办法用单个解决方案替换两个仅在类型上不同的相似函数?
- C++ 字符串,用于删除字符'b'并将字符'a'替换为两个'd'的构建函数
- 将两个数字替换为给定数组中介于两个之间的单个数字
- 如何将百分号 (%) 替换为两个 %?
- 使用c++将字符串中的单引号替换为两个单引号
- 在std::list中合并(将两个项目融合在一起,用融合替换)项目的算法(即破坏性聚类)
- 为什么两个不同的文本字符串不能替换为 = 运算符?
- 替换两个不同数组之间的字符
- 是否可以用模板函数替换两个相似的成员函数?
- 是否有一种快速的方法来替换两个地图内容
- 如何使用std::string将所有出现的一个字符替换为两个字符