我必须用字符串中的 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/