Skip to content

Instantly share code, notes, and snippets.

@jshardy
Created February 26, 2019 09:12
Show Gist options
  • Save jshardy/4f76069b333cabcaf05a2af15e97096b to your computer and use it in GitHub Desktop.
Save jshardy/4f76069b333cabcaf05a2af15e97096b to your computer and use it in GitHub Desktop.
Trim
/**********************************************************************
* Function: trim_string(" my string ")
* Purpose: trims spaces from front and back.
* Precondition: a string pointer
* Postcondition: string without leading or following spaces
************************************************************************/
void trim_string(char *string)
{
left_trim(string);
right_trim(string);
}
/**********************************************************************
* Function: left_trim(" my string")
* Purpose: trims spaces from front and back.
* Precondition: a string pointer
* Postcondition: string without leading spaces`
************************************************************************/
void right_trim(char *string)
{
//find the end of string
while(*string != 0)
string++;
//now were at the end. Backup one and see if space
string--;
while(*string == ' ')
*(string--) = 0;
}
/* Belongs in its own file */
/**********************************************************************
* Function: right_trim("my string ")
* Purpose: trims spaces from end.
* Precondition: a string pointer
* Postcondition: string without ending spaces.
************************************************************************/
void left_trim(char *string)
{
char *begin = string;
//front spaces removal
while(*string == ' ')
string++;
//did we have spaces? copy over them
if (string != begin)
memmove(begin, string, strlen(string) + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment