Deleting extra spaces in a string - C

Viewed 20

I need to write a function that deletes the spaces in the beginning and the end of a string. I tried this, but it's not working and I don't know exactly what I'm doing wrong. Why this code isn't good?

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

void CutSpaces(char str[]){
    char s[] = {};
    for (int i, j = 0; str[i] != '\0'; i++){
        if (str[i] != ' '){
            s[j] = str[i];
            j++;
        } 
        else if ((str[i] == ' ') && (str[i+1] != ' ')) {
            s[j] = str[i];
            j++;
        } 
    }
   printf("%s\n", s); 
}

int main(){
    char str[] = "   hello world   ";
    CutSpaces(str);
    return 0;
}
0 Answers
Related