Dave's Brain

Browse - Programming Tips - How can I delete trailing space from a string?

Date: 2009mar30
Language: C/C++
Keywords: trim

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< }

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.