如何将百分号 (%) 替换为两个 %?

How can I replace percent sign (%) with two %'s?

本文关键字:替换 两个 百分      更新时间:2023-10-16

我想尝试用两个%%符号替换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::findstd::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();
  }
}