How do I trim leading/trailing whitespace in a standard way?

后端 未结 30 2003
一个人的身影
一个人的身影 2020-11-22 02:06

Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I\'d roll my own, but I would think this is a common problem wit

30条回答
  •  忘了有多久
    2020-11-22 02:27

    Here i use the dynamic memory allocation to trim the input string to the function trimStr. First, we find how many non-empty characters exist in the input string. Then, we allocate a character array with that size and taking care of the null terminated character. When we use this function, we need to free the memory inside of main function.

    #include
    #include
    
    char *trimStr(char *str){
    char *tmp = str;
    printf("input string %s\n",str);
    int nc = 0;
    
    while(*tmp!='\0'){
      if (*tmp != ' '){
      nc++;
     }
     tmp++;
    }
    printf("total nonempty characters are %d\n",nc);
    char *trim = NULL;
    
    trim = malloc(sizeof(char)*(nc+1));
    if (trim == NULL) return NULL;
    tmp = str;
    int ne = 0;
    
    while(*tmp!='\0'){
      if (*tmp != ' '){
         trim[ne] = *tmp;
       ne++;
     }
     tmp++;
    }
    trim[nc] = '\0';
    
    printf("trimmed string is %s\n",trim);
    
    return trim; 
     }
    
    
    int main(void){
    
    char str[] = " s ta ck ove r fl o w  ";
    
    char *trim = trimStr(str);
    
    if (trim != NULL )free(trim);
    
    return 0;
    }
    

提交回复
热议问题