Last active
April 3, 2023 02:55
-
-
Save akmsw/ebfd2d1c142b1bce2adc162fca77ce61 to your computer and use it in GitHub Desktop.
Trim a string in C
This file contains 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
/** | |
* @brief This function removes the blank spaces from a | |
string that are at the beginning and end of it. | |
* | |
* @details The string is traversed from the beginning | |
* until the first character is found, which | |
* will be set as the trimmed string beginning. | |
* Thereafter, the same is done from the end of | |
* the string until the last character is found, | |
* which will be set as the trimmed string end. | |
* At the end of the trimmed string, the special | |
* end-of-string character is placed. | |
* If the given string is empty, it is returned | |
* as it came. | |
* | |
* @param str String to be trimmed. | |
* | |
* @return The trimmed string. | |
*/ | |
char *strtrim(char *str) | |
{ | |
while ((*str == ' ') || (*str == '\t') || (*str == '\n')) | |
str++; | |
if (*str == 0) | |
return str; | |
char *end = str + strlen(str) - 1; | |
while ((end > str) && ((*end == ' ') || (*end == '\t'))) | |
end--; | |
end[1] = '\0'; | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment