K&R c programming book 3.7 trim function example

Viewed 100

I've been following K&R book 2nd version for c programming, but in 3.7 part, here is the screenshot of the function and my code part:

enter image description here

#include <stdio.h>
#include <string.h>
/* trim: removing the trailing blanks, tabs and newlines  */
int trim(char s[]);
int main(){
    char s[] = "hello,world       \t\t\t\t\n\n\n\n";
    printf("%s\n", s);
    int length = trim(s);
    printf("%d\n", length);
    return 0;
}
int trim(char s[]){
   int n;
   for (n = strlen(s) -1 ; n >= 0 ; n--)
       if (s[n] != ' ' && s[n] != '\n' && s[n] != '\t')
            break;
   s[n+1] = '\0';
   return n;
}

The following is the output I get from running it:

enter image description here

Obviously the result length is 11, "hello,world", but the program outputs 10, the reason is s[n+1] = '\n', instead of s[++n];I think it should be s[++n], otherwise I will get the wrong output ==> 10, how to deal with it? could anyone plz take a look at it?

2 Answers

I would iterate over length and look ahead (behind?) one element to see if we need to trim it:

int trim(char s[]) {
    int n;
    for(n = strlen(s); n > 0; n--)
        if(s[n-1] != ' ' && s[n-1] != '\t' && s[n-1] != '\n')
            break;
    s[n] = '\0';
    return n;
}

In my opinion the book does not cleanly define the meaning of the return value.
But nearly:

looking for the first character that is not ...

I think that returning 10 matches that, if it is to be considered the definition.
So the 10 actually seems to be the correct value to me, it is the position of the "first" (or "last") non-white space character before/from the end of the string.

To answer the question "How to deal with it?":
You might not actually care, if you only use the modified string and not the return value.
If you do use the return value you need to use it according to the definition (if you consider the quoted text to be the definition), i.e. in order to get the length you have to increment by one in the using/calling function (not in the called function).
Or you modify the function as you described. That option only exists if you "own" the code (which in your own project and tutorials you do...). Keep in mind however, that this option will usually NOT be available in professional context of larger projects. There the APIs and behaviour is defined elsewhere and cannot be changed locally.

I do by the way agree and feel with you (your implicit rejection of the probable definition) and at least one commenter. The return value definition "position of last non-white character" is not one which jumps to mind....

Related