Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <ctype.h>
- char * trim(const char *str)
- {
- if(str == NULL)
- return NULL;
- // Trim leading space
- while(isspace(*str)) str++;
- if(*str == 0) // If string is "empty" - contains only whitespaces -- return null
- {
- return NULL;
- }
- // Trim trailing space
- const char * end = str + strlen(str) - 1; // go to end of string
- while(end > str && isspace(*end)) end--; // go to first nonspace char
- end;
- // Set output size to minimum of trimmed string length and buffer size minus 1
- size_t out_size = (end - str) + 1; // Do not forget to 0
- char *out = malloc(out_size * sizeof(char));
- // Copy trimmed string and add null terminator
- memcpy(out, str, out_size);
- out[out_size] = 0;
- return out;
- }
- int main(void)
- {
- const char * str = " \t\t AHOJ SVET \t\t ";
- printf("String without trim: \"%s\"\n", str);
- char *trimmed = trim(str);
- printf("Trimmed string: \"%s\"\n", trimmed);
- free(trimmed);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement