Http://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way
Remove the Space key at the beginning and end of a string (the idea can be extended to other symbols ).
There are two scenarios,
1. the first is the space that can be changed for this string, such as the character array, allocated in the heap (calloc and malloc), and some buffer (transmitted over TCP, however, the above method is also used, but I just want to share it with you, haha ).
char *trimwhitespace(char *str){ char *end; // Trim leading space while(isspace(*str)) str++; if(*str == '\0') // All spaces? return str; // Trim trailing space end = str + strlen(str) - 1; while(end > str && isspace(*end)) end--; // Write new null terminator *(end+1) = '\0'; return str;}
2. If you cannot change the input characters, you need to apply for a space (array, heap) to put the changed string.
char *trimwhitespace(char *str){ char *end; // Trim leading space while(isspace(*str)) str++; if(*str == '\0') // All spaces? return str; // Trim trailing space end = str + strlen(str) - 1; while(end > str && isspace(*end)) end--; // Write new null terminator *(end+1) = '\0'; return str;}size_t trimwhitespace(char *out, size_t len, const char *str){ if(len == 0) return 0; const char *end; size_t out_size; // Trim leading space while(isspace(*str)) str++; if(*str == '\0') // All spaces? { *out = '\0'; return 1; } // Trim trailing space end = str + strlen(str) - 1; while(end > str && isspace(*end)) end--; end++; // Set output size to minimum of trimmed string length and buffer size minus 1 out_size = (end - str) < len-1 ? (end - str) : len-1; // Copy trimmed string and add null terminator memcpy(out, str, out_size); out[out_size] = '\0'; return out_size;}
Note: after testing, I found bugs in the wood. The logic is relatively simple. I first judge the passed strings to see if they are empty or pure space characters, then eliminate the header and tail, and then pass them out.
Looking at the discussion from foreigners, there is a doubt about the first one, that is, if you input a dynamic generation, You Need To Do It Yourself In the main function (assuming it is called in main), free of charge, otherwise, the memory is leaked ~~~ Of course, the array doesn't matter ~~~
Well, it is best to describe ~~~ in the comment ~~~
PS: check whether there are any bugs ~~~