In my code, I have char array and here it is: char pIPAddress[20];
And I’m setting this array from a string with this code:strcpy(pIPAddress,pString.c_str());
After this loading; for example pIPAddress value is “192.168.1.123 “. But i don’t want spaces. I need to delete spaces. For this i did this pIPAddress[13]=0;.
But If IP length chances,It won’t work. How can i can calculate space efficient way? or other ways?
Thnx
The simplest approach that you can do is to use the
std::remove_copyalgorithm:The next question would be why would you want to do this, because it might be better not to copy it into an array but rather remove the spaces from the string and then use
c_str()to retrieve a pointer…EDIT As per James suggestion, if you want to remove all space and not just the
' 'character, you can usestd::remove_copy_ifwith a functor. I have tested passingstd::isspacefrom the<locale>header directly and it seems to work, but I am not sure that this will not be problematic with non-ascii characters (which might be negative):The horrible cast in the last argument is required to select a particular overload of
isspace.[1] The
*... = 0;needs to be added to ensure NUL termination of the string. Theremove_copyandremove_copy_ifalgorithms return anenditerator in the output sequence (i.e. one beyond the last element edited), and the*...=0dereferences that iterator to write the NUL. Alternatively the array can be initialized before calling the algorithmchar ip[20] = {};but that will write\0to all 20 characters in the array, rather than only to the end of the string.