c++ - 用C++中的字符串替换空格

标签 c++ string replace

我必须用字符串中的 0(整数 0)替换空格。即空终止此字符串中的每个单词。

char data[] = "r1 2 3 1.0kohm \n v1 1 0 5.5v";

当我这样做时:

int index = 0;
char token[50];
while (data[index] != '\0')
{
     token[index] = 0;
     index++;                 
}

但它替换为字符 0 而不是整数 0。

最佳答案

I have to replace spaces with 0 (integer 0) in a string.

您可以使用 std::replace 轻松实现此目的算法:

std::string data = "r1 2 3 1.0kohm \n v1 1 0 5.5v";
std::replace(data.begin(), data.end(), ' ', '\0');

这也适用于普通的 char数组:

char data[] = "r1 2 3 1.0kohm \n v1 1 0 5.5v";
std::replace(std::begin(data), std::end(data), ' ', '\0');

您需要包含 <algorithm> std::replace 的 header .

关于c++ - 用C++中的字符串替换空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20902857/

相关文章:

c++ - C++程序输出错误

c++ - 在 C++ 中使用 c_str() 将字符串转换为 double

arrays - Perl 替换文件中的多个字符串

pandas - 根据索引 pandas 替换值

c++ - 如何计算以任意字符集编码的字符串中的字符数

c++ - 如何将 ampl 中的集合表示为 C++ 中的 vector ?

php - 如何将字符串截断为 PHP 中的前 20 个单词?

Java: String.replaceAll(regex, replacement);

c++ - memcpy 不复制到缓冲区

c - 将字符串文字分配给数组时出错