c - Function removes extra spaces but leaves one space between words in a char pointer -


i need function take char pointer char *s = "abc def gf ijklmn". if passed through function int space_remove(char *) should return number of spaces , modify string , take out spaces.

int space_remove(char *s) {     int = 0, ic = 1, r = 0,space = 0;     //char *sp = (char *) malloc(strlen(s) * sizeof(char));     char sp[256];     while (*(s+i) != '\0'){         if (*(s+i) == ' ' && *(s+i+1) == ' '){             space = 1;             r++;         }         if (space){             sp[i] = *(s+i+r);             i++;         }          else if (!space){             sp[i] = *(s+i+r);             i++;          }         else {             sp[i] = *(s+i+r);             i++;         }     }     sp[i+1] = '\0';     printf("sp:%s \n",sp);     s = sp;     //free(sp);     return r; } 

any here?

if the string "abc (10 spaces) def (20 spaces) hijk" should return "abc(1 space) def (1 space) hijk"

there 2 issues

  1. reset space 0 in while loop.

  2. do not return sp in local char array. can copy string in s instead.

    strcpy(s, sp);

instead of

s = sp; 

strcpy safe length of sp should @ max length of s when there nothing trim.


Comments