How to remove multiple spaces from a string in C

3 Answers

0 votes
#include <stdio.h>
#include <string.h>

int main(void) {
    char s[64] = " c    c++     python     java     ", tmp[64];
    int i = 0, j = 0;

    while (s[i])  {
        if (!(s[i] == ' ' && s[i + 1] == ' ') & i != 0) {
            tmp[j] = s[i];
            j++;
        }
        i++;
    }

    tmp[j - 1] = '\0';
    strcpy(s, tmp);
    
    printf("%s", s);
}




/*
run:
 
c c++ python java
 
*/

 



answered Jun 24, 2021 by avibootz
0 votes
#include <stdio.h>

void remove_multiple_spaces_from_a_string(char* s) {
    int j = 0;
    for (int i = 0; s[i]; i++)
        if (s[i] !=' ' || (i > 0 && s[i - 1] != ' '))
            s[j++] = s[i];
    s[j] = '\0';
}

int main(void) {
    char s[64] = " c    c++     python     java     ", tmp[64];

    remove_multiple_spaces_from_a_string(s);

    printf("%s", s);
}




/*
run:
 
c c++ python java 
 
*/

 



answered Jun 24, 2021 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

void remove_multiple_spaces_from_a_string(char* s) {
    char *p;
      
    while ((p = strstr(s, "  "))) {
        strcpy(p, p + 1);
    }
    if (s[0] == ' ') strcpy(s, s + 1);
    if (s[strlen(s) - 1] == ' ') s[strlen(s) - 1] = '\0';
}
 
int main(void) {
    char s[64] = " c    c++     python     java         ", tmp[64];
 
    remove_multiple_spaces_from_a_string(s);
 
    printf("%s", s);
}
 
 
 
 
/*
run:
  
c c++ pyhon java
  
*/

 



answered Jun 24, 2021 by avibootz
...