There is an array of char, for example, char n1 [] = "a bc def ghijk"; you need to replace all second spaces with emptiness, you went something like this

void clean(char* n){ bool f=false; for(int i=0;n[i]!=NULL;i++){ if(f==false && n[i]==' ' && n[i+1]==' '){ f=true; }else if(n[i]==' ' && f==true){ n[i]=(char)00; f=false; } } cout<<n; } int main() { char n1[] = "a bc def ghijk"; clean(n1); } 

but then the output is an empty string, or rather 1 character, and where the idea is to remove the empty string character.

  • The phrase "all second spaces" is not entirely clear. Need to remove duplicate spaces? - Vlad from Moscow

1 answer 1

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; } 
  • everything would be fine, but you can’t use #include <cstring> - user2420249
  • @ user2420249 See my updated answer. - Vlad from Moscow
  • But how can the first and last character be something to take into account - user2420249
  • @ user2420249 Write a separate trim function or change the function that I showed you. To do this, simply find the first non-whitespace character in the function .. - Vlad from Moscow
  • with the first understood, with the last did not understand - user2420249