If your goal is to change the string, then the strategy could be
1) Find the first space character. If no space character was found, we can end processing. If a space is found, then this is the first position to change and the first position to check (these are distinct positions, even though they start out at the same place).
2) Process the string using these two indices, one pointing to the position to check, and the other pointing to the position to change.
3) If the position to check is not a space, copy it to the position to change and increment the position to change.
4) Increment the position to check. Go to step 3) until the end of string is encountered (position to check is at the end-of-string).
5) Null terminate the string at the position to change. Done.
Here is an implementation of the above:
#include <iostream>
#include <cstring>
int main()
{
char str[] = "Hello, my name is John";
size_t len = strlen(str);
size_t change_position = 0;
// find the first space character
for (change_position = 0; change_position < len; ++change_position)
{
if (str[change_position] == ' ')
break; // found it
}
if (change_position != len) // if we found a space character
{
// starting from the first space
for (size_t check_position = change_position; check_position < len; ++check_position)
{
// if the check position is not a space
if (str[check_position] != ' ')
{
// copy it to the change position
str[change_position] = str[check_position];
// update change position
++change_position;
}
}
}
// finish up by null-terminating the string
str[change_position] = '\0';
std::cout << str;
}
Live Example