Dave's Brain

Browse - Programming Tips - How do I remove the leading whitespace from a string?

Date: 2007nov17
Language: C/C++
Keywords: trim, space, blank, tab, tabs, newline, newlines, zero, zeros

Q.  How do I remove the leading whitespace from a string?

A.  Here's a pretty nice way to do it:

// First, a helper function inline char *Shuffle(char *dest, const char *src) { return (char *) memmove(dest, src, strlen(src) + sizeof(char)); } void TrimLeadingSpace(char *s) { const char * p; for (p = s; *p; p++) { if (!isspace(*p)) break; } Shuffle(s, p); }
Example use:
main() { char buf[100] = " hello"; printf("before=>%s<\n", buf); TrimLeadingSpace(buf); printf(" after=>%s<\n", buf); }
You can use remove leadings zeros this way:
void TrimLeadingZeros(char *s) { while(*s == '0') { Shuffle(s, s+1); } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.