/*---------------------------------------------------------- * HTBLA-Leonding * --------------------------------------------------------- * Title: Trim String * Author: Marc Tismonar * ---------------------------------------------------------- * Description: * Implementation of 'trim' functionality. * ---------------------------------------------------------- */ #include #include #include #include "trim.h" // private functions bool is_whitespace(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; } void shift(char* string, int start, int end) { int i; for (i = 0; i <= end - start; i++) { string[i] = string[i + start]; } string[i] = '\0'; } void override_all(char* string) { for (int i = 0; i < strlen(string); i++) { string[i] = ' '; } } /** * Provides the trimmed string WITHOUT making a copy * of the source string. * Trimming means that leading and trailing whitespace * characters are removed. * * Whitespace characters are: * - space (' '), * - tabulator ('\t') * - new line ('\n') * - line feed ('\r') * @param string The string to be trimmed. * @return The trimmed string. */ char* trim(char* string) { if (string == 0) { return 0; } int start = 0; while (string[start] != '\0' && is_whitespace(string[start])) { start++; } // if empty or only whitespace if (string[start] == '\0') { string[0] = '\0'; return string; } int end = strlen(string) - 1; while (end > start && is_whitespace(string[end])) { end--; } // shift if (start > 0) { shift(string, start, end); } else { string[end + 1] = '\0'; } return string; } /** * Provides the trimmed string as COPY of the source string. * Trimming means that leading and trailing whitespace * characters are removed. * * Whitespace characters are: * - space (' '), * - tabulator ('\t') * - new line ('\n') * - line feed ('\r') * @param string The string to be trimmed. * @param trimmed_string Container which takes the trimmed * version of source. This function expects a buffer that * is large enough for carrying the trimmed string. */ void trim_cpy(char* string, char* trimmed_string) { if (string == 0 || trimmed_string == 0) { return; } if (strlen(string) == 0) { trimmed_string[0] = '\0'; return; } override_all(trimmed_string); trimmed_string = strncpy(trimmed_string, string, strlen(string)); trimmed_string = trim(trimmed_string); }