How to remove spaces that are in a string sentence

后端 未结 5 1793
-上瘾入骨i
-上瘾入骨i 2021-01-25 13:48

I am trying to write a code to remove all the leading, trailing and middle of the sentence spaces but to keep only one space between the words.

For example if the input

5条回答
  •  闹比i
    闹比i (楼主)
    2021-01-25 14:25

    #include 
    #include 
    #include 
    
    char** split(const char *str, const char *delimiter, size_t *len){
        char *text, *p, *first, **array;
        int c;
        char** ret;
    
        *len = 0;
        text=strdup(str);//strdup not standard
        if(text==NULL) return NULL;
        for(c=0,p=text;NULL!=(p=strtok(p, delimiter));p=NULL, c++)//count item
            if(c==0) first=p; //first token top
    
        ret=(char**)malloc(sizeof(char*)*c+1);//+1 for NULL
        if(ret==NULL){
            free(text);
            return NULL;
        }
        //memmove?
        strcpy(text, str+(first-text));//skip until top token
        array=ret;
        for(p=text;NULL!=(p=strtok(p, delimiter));p=NULL){
            *array++=p;
        }
        *array=NULL;
        *len=c;
        return ret;
    }
    
    void free4split(char** sa){
        char **array=sa;
    
        if(sa!=NULL){
            free(array[0]);//for text
            free(sa);      //for array
        }
    }
    
    int main(void){
        char str[100] = "    This    is my     string    ";
        char **words;
        size_t len=0;
        int i;
    
        words = split(str, " \t", &len);
        *str = '\0';
        for(i = 0;i

提交回复
热议问题