Dave's Brain

Browse - programming tips - trim trailing space

Date: 2009mar30
Language: C/C++

Q.  How can I delete trailing space from a string?

A.  Turn trailing spaces into NUL's as this function does:

void TrimTrailingSpace(char *s)
{
	for (char *p = &s[strlen(s)-1]; p >= s; p--)
	{
		if (!isspace(*p)) break;
		*p = '\0';
	}
}

void ExampleUse()
{
	char	buf[100];

	lstrcpyn(buf, "Hello World     ", sizeof(buf));
	TrimTrailingSpace(buf);
	printf(">%s<\n", buf);
	// Will output >Hello World<
}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, 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.
Advertisements: