Reputation: 72
I have to replace spaces with 0
(integer 0) in a string. i.e. to null terminate each word in this string.
char data[] = "r1 2 3 1.0kohm \n v1 1 0 5.5v";
when I do like this:
int index = 0;
char token[50];
while (data[index] != '\0')
{
token[index] = 0;
index++;
}
but it replaces with character 0 not integer 0.
Upvotes: 1
Views: 1987
Reputation: 3997
Better to use @juanchopanza solution. But if you don't want to use STL, modify your code to be:
const int len = strlen(data);
for (int i = 0; i < len; i++)
{
if (data[i] == ' ')
data[i] = '\0';
}
Upvotes: 1
Reputation: 227390
I have to replace spaces with 0 (integer 0) in a string.
You can achieve this easily with the std::replace
algorithm:
std::string data = "r1 2 3 1.0kohm \n v1 1 0 5.5v";
std::replace(data.begin(), data.end(), ' ', '\0');
This would also work with a plain char
array:
char data[] = "r1 2 3 1.0kohm \n v1 1 0 5.5v";
std::replace(std::begin(data), std::end(data), ' ', '\0');
You will need to include the <algorithm>
header for std::replace
.
Upvotes: 5