Skip to content

Instantly share code, notes, and snippets.

@keejelo
Last active March 15, 2022 07:42
Show Gist options
  • Select an option

  • Save keejelo/77ed1a8aceaf3e7ea0637424182ae561 to your computer and use it in GitHub Desktop.

Select an option

Save keejelo/77ed1a8aceaf3e7ea0637424182ae561 to your computer and use it in GitHub Desktop.
Trim string whitespace
//--------------------------------------------------------------------------------
// Filename: trim_string_whitespace.c
//--------------------------------------------------------------------------------
// ** Trim leading and trailing whitespace
//--------------------------------------------------------------------------------
char *trim(char *s)
{
char c[] = "\x20\t\n\v\f\r"; // whitespace characters
int i, j;
for(i = 0; s[i] == c[0] || s[i] == c[1] || s[i] == c[2] || s[i] == c[3] || s[i] == c[4] || s[i] == c[5]; i++);
for(j = 0; s[i]; i++)
{
s[j++] = s[i];
}
s[j] = '\0';
for(i = 0; s[i] != '\0'; i++)
{
if(s[i] != c[0] && s[i] != c[1] && s[i] != c[2] && s[i] != c[3] && s[i] != c[4] && s[i] != c[5])
{
j = i;
}
}
s[j+1] = '\0';
return s;
};
//--------------------------------------------------------------------------------
// ** END: Trim leading and trailing whitespace
//--------------------------------------------------------------------------------
/*
// Example usage:
int main()
{
char str[] = " test ";
trim(str);
printf("%s", str);
return 0;
};
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment