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