•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the C section within the Software Development category of DaniWeb, a massive community of 402,507 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,842 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C advertiser: Programming Forums
Here is a simple implementation of implementing a simple Left trim (ltrim) and Right trim(rtim) of unwanted characters from a C style string. (null terminated strings). Doesn't suffer the overheads of the memmove implementation in which the worst case scenario (a string containing all junk characters) is approx. N^2 / 2.
Comments, constructive criticisims are welcome.
Comments, constructive criticisims are welcome.
Last edited : Apr 29th, 2007.
#include <stdio.h> char* rtrim(char* string, char junk); char* ltrim(char* string, char junk); int main() { char testStr1[] = " We like helping out people "; char testStr2[] = " We like helping out people "; char testStr3[] = " We like helping out people "; printf("|%s|", testStr1); printf("\n|%s|", ltrim(testStr1, ' ')); printf("\n\n|%s|", testStr2); printf("\n\n|%s|", rtrim(testStr2, ' ')); printf("\n\n|%s|", testStr3); printf("\n|%s|", ltrim(rtrim(testStr3, ' '), ' ')); getchar(); return 0; } char* rtrim(char* string, char junk) { char* original = string + strlen(string); while(*--original == junk); *(original + 1) = '\0'; return string; } char* ltrim(char *string, char junk) { char* original = string; char *p = original; int trimmed = 0; do { if (*original != junk || trimmed) { trimmed = 1; *p++ = *original; } } while (*original++ != '\0'); return string; } /* | We like helping out people | |We like helping out people | | We like helping out people | | We like helping out people| | We like helping out people | |We like helping out people| */
Comments (Newest First)
~s.o.s~ | Rebellion Revamped | May 26th, 2007
Ene Uran | Veteran Poster | May 24th, 2007
•
•
•
•
How to you handle tabs?
StrikerX | Newbie Poster | May 23rd, 2007
•
•
•
•
Nice one, thanks .
Nutty | Newbie Poster | May 3rd, 2007
•
•
•
•
it is a good, i like this type of programe
Post Comment
•
•
•
•
DaniWeb Marketplace (Sponsored Links)
If you will notice, this is not a generic function, the way we have in Python, Ruby and other languages. You need to pass the character to be stripped. If you want to strip off tabs, pass the junk character to be '\t'.