/* spaces.c * remove spaces from a string in-place - a common interview question */ #include #include /* Simple implementation that is also efficient */ void remove_spaces1(char *s) { int i, j; /* i: input cursor, j: output cursor */ for(j=i=0;s[i];i++) { if(s[i]==' ') continue; s[j++]=s[i]; } s[j]=0; } /* Second variation of above that is more common to see */ void remove_spaces2(char *s) { int i, j; /* i: input cursor, j: output cursor */ for(j=i=0;s[i];i++) { if(s[i]!=' ') { s[j++]=s[i]; } } s[j]=0; } /* very inefficient version that is typical to see in interviews */ void remove_spaces3(char *s) { int len; while(*s) { /* find next space */ s=strchr(s, ' '); if(!s) { /* TODO: null terminate */ return; /* done - no more spaces */ } len=strlen(s); memmove(s, s+1, len); } } /* succinct implementation that implicitly null terminates */ void remove_spaces4(char *s) { char *p=s; do { if(*s!=' ') { *p++=*s; } } while(*s++); } /* Simple implementation using two loops */ void remove_spaces5(char *s) { int i, j; /* i: input cursor, j: output cursor */ i=j=0; while(s[i]) { while(s[i]==' ') i++; /* skip over spaces on input */ s[j++]=s[i++]; } s[j]=0; } /* a very common approach for inexperienced developers who are used to reusing code templates */ void remove_spaces6(char *s) { int i, j, len; len=strlen(s); j=0; i=0; while(i<=len) { /* usually they do i ", j, buf); remove_spaces_n[j](buf); printf("\"%s\"\n", buf); } } return 0; }