Created
July 9, 2011 17:31
-
-
Save amireh/1073775 to your computer and use it in GitHub Desktop.
Trim strings in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <malloc.h> | |
| #include <string.h> | |
| int is_ws(char c) { | |
| return c == ' '; | |
| } | |
| int trim(const char* src, char** dst) { | |
| if (strlen(src) == 0) | |
| return 0; | |
| size_t src_size = strlen(src); | |
| int lp /* left padding */ = 0; | |
| int rp /* right padding */ = 0; | |
| while (is_ws(src[lp]) && ++lp);; | |
| while (is_ws(src[src_size-rp-1]) && ++rp);; | |
| /* optionally reallocate to not waste unused memory */ | |
| /* NOTE: change this to malloc if you don't want to pre-allocate the out buffer */ | |
| if (lp+rp != 0) | |
| (*dst) = (char*)realloc((*dst), sizeof(char) * src_size-lp-rp); | |
| int i; | |
| for (i = lp; i < src_size-rp; ++i) | |
| (*dst)[i-lp] = src[i]; | |
| (*dst)[src_size-lp-rp] = '\0'; | |
| return lp+rp; | |
| } | |
| int main(int argc, char** argv) { | |
| if (argc < 2) { printf("usage: trim string\n"); return 1; } | |
| char *bar = malloc(sizeof(char) * strlen(argv[1])); | |
| trim(argv[1], &bar); | |
| printf("Source string:\t'%s'\nTrimmed string:\t'%s'\n", argv[1], bar); | |
| free(bar); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment