#include <stdio.h> #include <string.h> void trim(char *s, const int len) { int end = len - 1; int start = 0; int i = 0; while ((start < len) && (s[start] <= ' ')) { start++; } while ((start < end) && (s[end] <= ' ')) { end--; } if (start > end) { memset(s, '\0', len); return; } for (i = 0; (i + start) <= end; i++) { s[i] = s[start + i]; } memset((s + i), '\0', len - i); } int main() { char s[] = " srikanth s \n"; char empty[] = ""; char newline[] = "\n"; char double_newline[] = "\n\n"; char single_char[] = " s "; trim(s, strlen(s)); printf("s = '%s'\n", s); trim(empty, strlen(empty)); printf("empty = '%s'\n", empty); trim(newline, strlen(newline)); printf("newline = '%s'\n", newline); trim(double_newline, strlen(double_newline)); printf("double_newline = '%s'\n", double_newline); trim(single_char, strlen(single_char)); printf("single_char = '%s'\n", single_char); return 0; }
The main() is just for testing the function, let's see how it went.
$ gcc -Wall -o go trim.c $ ./go s = 'srikanth s' empty = '' newline = '' double_newline = '' single_char = 's'
This function doesn't create a new char[] for the trimmed string, it modifies the original. Let me know if you've got an optimized version than this, I'll be interested to learn.
(Edit: Thanks to my colleague Hiren for catching a nasty bug. The memset at the end,
memset((s + i), '\0', len)
had a bug. It should've been memset((s + i), '\0', len - i)
. *So, that brings us to the disclaimer. Take the code at your own risk. I'm not responsible if it formats your hard drive or if it kills your cat.)That's it, see you later, I've gotta go trim.
2 comments:
Thanks man, this function helps me in a program that i had to do last week
good work
Robson, I'm glad it helped you.
Post a Comment