Dave's Brain

Browse - programming tips - trim leading space

Date: 2007nov17
Language: C
Keywords: space, blank, tab, tabs, newline, newlines

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

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

inline char *Shuffle(char *dest, const char *src)
{
	return (char *) memmove(dest, src, strlen(src) + sizeof(char));
}

void TrimLeadingSpace(char *s)
{
	while (isspace(*s))
	{
		Shuffle(s, s+1);
	}
}

void TrimLeadingSpaceSlightlyFaster(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);
}

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.