If I understand you correctly, then you need to remove all adjacent spaces in the line except the first one.
In this case, you can use the standard std::unique algorithm, declared in the std::algorithm header. for example
#include <iostream> #include <algorithm> #include <cstring> int main() { char s[] = "a bc def ghijk "; std::cout << "\"" << s << "\"\n"; std::unique( s, s + sizeof( s ), []( char c1, char c2 ) { return ( c1 == c2 ) && ( c1 == ' ' ); } ); std::cout << "\"" << s << "\"\n"; }
The output of the program to the console:
"a bc def ghijk " "a bc def ghijk "
Instead of an expression in the algorithm call
s + sizeof( s )
you can use the expression
s + std::strlen( s ) + 1
If you yourself need to write such a function, then such a function may look, for example, as follows:
#include <iostream> char * remove_blanks( char *s ) { if ( *s ) { char *p = s; char *q = p + 1; do { if ( *p != ' ' || *q != ' ' ) { ++p; if ( p != q + 1 ) *p = *q; } ++q; } while ( *p ); } return s; } int main() { char s[] = "a bc def ghijk "; std::cout << "\"" << s << "\"\n"; std::cout << "\"" << remove_blanks( s ) << "\"\n"; }
Output to console:
"a bc def ghijk " "a bc def ghijk "
If you need to write a function that also removes leading and trailing spaces, then such a function might look like this
char * remove_blanks( char *s ) { char *p = s; char *q = s; while ( *q == ' ' ) ++q; while ( *p ) { if ( *q == '\0' && *( p - 1 ) == ' ' ) { *( p - 1 ) = *q; } else { if ( *q != ' ' || *( q - 1 ) != ' ' ) { if ( p != q ) *p = *q; if ( *p ) ++p; } ++q; } } return s; }