Are these removal methods "\ n" to the left of fgets preserved in relation to performance?

I am currently studying C, if this question seems easy or newbie, then you know why.

So, I know there are many ways to remove to the '\n'left of fgets(), as already discussed on SO here , here and here .

I am going to focus this topic on these three methods:

  • char * strchr (const char * s, int c);

    if (fgets(sentence, 11, stdin) != NULL) {
        p = strchr(sentence, '\n');
        *p = '\0';
    }
    
  • char * strtok (char * str, const char * delim);

    if (fgets(sentence, 11, stdin) != NULL)
        token = strtok(sentence, "\n");
    
  • size_t strcspn (const char * s, const char * reject);

    if (fgets(sentence, 11, stdin) != NULL)
        sentence[strcspn(sentence, "\n")] = '\0';
    

, p token char *p = NULL, *token = NULL;

, , , ?

, ( , , ), , strspn , , , .

, , , . , time ./executable , SO. , .

- , ?

EDIT: , , strcspn .

+4
2

,

if (fgets(sentence, 11, stdin) != NULL) {
    p = strchr(sentence,'\n');
    p = '\0';
    //^^ must be *p 
}

, . p NULL, undefined.

,

    if ( p ) *p = '\0';

    if ( ( p = strchr(sentence,'\n') ) != NULL ) *p = '\0';

, .

, , .

if (fgets(sentence, 11, stdin) != NULL)
    token = strtok(sentence, "\n");

. strtok , . , .

,

if (fgets(sentence, 11, stdin) != NULL)
    sentence[strcspn(sentence, "\n")] = 0;

, .

, ++

if ( char *p = strchr( sentence, '\n' ) ) *p = '\0';

C :)

sentence[strcspn(sentence, "\n")] = '\0';
+2

, .

:

strchr

if (fgets(sentence, 11, stdin) != NULL) {
    p = strchr(sentence, '\n');
    *p = '\0';
}

, p NULL. , , sentence \n, , , sentence , \n, . :

if (fgets(sentence, 11, stdin) != NULL) {
    char *p = strchr(sentence, '\n');
    if (p != NULL)
        *p = '\0';
    ...
}

strchrnul

C strchrnul :

char *strchrnul(const char *s, int c);

c s \0, . \n:

if (fgets(sentence, 11, stdin) != NULL) {
    *strchrnul(sentence, '\n') = '\0';
    ...
}

, C .

strtok

if (fgets(sentence, 11, stdin) != NULL) {
    token = strtok(sentence, "\n");
    ...
}

: strtok . , strtok. , , . strtok: strtok_r, .

, user3121023, strtok \n, . . (strtok , .)

StrLen

strlen. :

if (fgets(sentence, 11, stdin) != NULL) {
    sentence[strlen(sentence) - 1] = '\0';
    ...
}

:

  • sentence \n , strchr. \n .

  • sentence , undefined. sentence , C: , fgets() .

:

if (fgets(sentence, 11, stdin) != NULL) {
    size_t len = strlen(sentence);
    if (len > 0 && sentence[len - 1] == '\n')
        sentence[--len] = '\0';
    // useful side effect: len has been updated.
    ...
}

strcspn

if (fgets(sentence, 11, stdin) != NULL) {
    sentence[strcspn(sentence, "\n")] = '\0';
    ...
}

. , sentence \n , . , .

strcspn , , C . , strtok, . , , strchr strlen, strlen 2 len > 0 sentence[len - 1] == '\n', .

, , 1- . , , strchr.

, strcspn C, GNU libc, Apple C. , gcc .

strchrnul .

, , , C... .

+4

Source: https://habr.com/ru/post/1625749/


All Articles