#include // The size of character arrays that we will use to store strings. #define BUFSIZE 500 // Remove any leading spaces from string. static void remove_leading_spaces(char *string) { char *s; // Make s point at the first non-space character for (s = string; *s == ' '; s++) ; if (s == string) // There are no leading spaces so simply return return; // Now work forward through the string, copying each // character to an earler position. while (*s != '\0') *string++ = *s++; // Mark the new end of the string *string = '\0'; } // Remove any spaces from the end of the string static void remove_trailing_spaces(char *string) { // ADD CODE HERE char *s; // Make s point at the first non-space character for (s = string; *s != '\0'; s++); //to go backwards till we find a non " " for(s--;*s==' ';s--); // jump forward one, so to access the first " " and set it to the end of the line \0 marker s++; *s='\0'; if (s == string) // There are no trailing spaces so simply return return; } // Replace any sequence of 2 or more space characters by a single space. static void remove_repeated_spaces(char *string) { // ADD CODE HERE char *s; char *n; s = string; n = string; while (*s != '\0') { *n = *s++; if ((*n == ' ') && (*s == ' ')) { while (*s != '\0') *string++ = *n++; } else { s++; n++; } //s++; //n++; } if(s == string) return; } // Read a line of input from the standard input and return 3 copies // of it in s1, s2 and s3. zero is returned if successful, -1 if // the input is at end-of-file. static int get_test_strings(char *s1, char *s2, char *s3) { // read a line to a maximum of BUFSIZE into the first string if (fgets(s1, BUFSIZE, stdin) == NULL) return -1; // Copy the first string into the other two strings. // Do not copy any trailing linefeed or carriage-return while (*s1 != '\0' && *s1 != '\n' && *s1 != '\r') *s3++ = *s2++ = *s1++; // terminate the two strings *s3 = *s2 = *s1 = '\0'; return 0; } int main(int argc, char **argv) { char buf1[BUFSIZE], buf2[BUFSIZE], buf3[BUFSIZE]; printf("Test string:"); while (get_test_strings(buf1, buf2, buf3) == 0) { remove_leading_spaces(buf1); remove_trailing_spaces(buf2); remove_repeated_spaces(buf3); printf("\twith leading spaces removed '%s'\n", buf1); printf("\twith trailing spaces removed '%s'\n", buf2); printf("\twith repeated spaces removed '%s'\n", buf3); printf("Test string:"); } printf("\n"); return 0; }