/* File: trim.c Name: Removes leading spaces, trailing spaces and extra spaces. */ /* Don't change anything from this line until the end of main. */ #include #include #include #include void trim_str(char *new_str, char *old_str) ; int main() { char *str, *trimmed ; int n ; str = readline("Enter a string: ") ; n = strlen(str) ; // allocate enough space for trimmed trimmed = malloc(n+1) ; if (trimmed == NULL) { printf("Oops, can't allocate %d bytes\n", n+1) ; return 1 ; } // Calls your trim function trim_str(trimmed, str) ; printf("Trimmed string = \"%s\"\n", trimmed) ; // deallocate memory free(str) ; free(trimmed) ; return 0 ; } /* End of main */ void trim_str(char *new_str, char *old_str) { // Suggested algorithm in comments // use variable i to index into old_str // use variable j to index into new_sr // initialize i and j // while ( 1 ) { // // skip over spaces, that is using a loop // add 1 to i until old_str[i] is not a space // // copy over non-spaces, that is using a loop // copy old_str[i] to new_str[j] // Note: need to stop when space or '\0' encountered // // if at end of old_str, stop // // otherwise, copy a space into new_str // // } // /* end of while loop */ // // add terminating '\0' to new_str // }