Add new versions of whitespace trimming functions

This commit is contained in:
twinaphex 2016-06-09 08:01:55 +02:00
parent a63fcc36aa
commit e4f25d9984
2 changed files with 58 additions and 0 deletions

View File

@ -47,6 +47,15 @@ char *string_ucwords(char* s);
char *string_replace_substring(const char *in, const char *pattern,
const char *by);
/* Remove leading whitespaces */
char *string_trim_whitespace_left(char *const s);
/* Remove trailing whitespaces */
char *string_trim_whitespace_right(char *const s);
/* Remove leading and trailing whitespaces */
char *string_trim_whitespace(char *const s);
RETRO_END_DECLS
#endif

View File

@ -118,3 +118,52 @@ char *string_replace_substring(const char *in,
return out;
}
/* Non-GPL licensed versions of whitespace trimming:
* http://stackoverflow.com/questions/656542/trim-a-string-in-c
*/
/* Remove leading whitespaces */
char *string_trim_whitespace_left(char *const s)
{
if(s && *s)
{
size_t len = strlen(s);
char *cur = s;
while(*cur && isspace(*cur))
++cur, --len;
if(s != cur)
memmove(s, cur, len + 1);
}
return s;
}
/* Remove trailing whitespaces */
char *string_trim_whitespace_right(char *const s)
{
if(s && *s)
{
size_t len = strlen(s);
char *cur = s + len - 1;
while(cur != s && isspace(*cur))
--cur, --len;
cur[isspace(*cur) ? 0 : 1] = '\0';
}
return s;
}
/* Remove leading and trailing whitespaces */
char *string_trim_whitespace(char *const s)
{
string_trim_whitespace_right(s); /* order matters */
string_trim_whitespace_left(s);
return s;
}