Last active
March 15, 2022 07:42
-
-
Save keejelo/77ed1a8aceaf3e7ea0637424182ae561 to your computer and use it in GitHub Desktop.
Trim string whitespace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //-------------------------------------------------------------------------------- | |
| // 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