i'm studying c, if question seems easy 1 or newbie ones, know why.
so, i know there lot of ways remove '\n' left fgets(), discussed on here, here , here.
i'm going focus topic these 3 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';
assume variables p , token declared char *p = null, *token = null;
they job but, far performance concerned, differ?
once, surfing on web (i'm sorry haven't proof of this, because forgot link) found strspn not real way if 1 interested in performance, hence question.
before posting on i've searched here without finding want know. i've tried profiling myself, both using time ./executable , this method found on so. had no luck, because results inconsistent.
can me finding out if profiled wrong or if equal?
edit : here link found strcspn not efficient.
this method written
if (fgets(sentence, 11, stdin) != null) { p = strchr(sentence,'\n'); p = '\0'; //^^ must *p } is incorrect because new line character can absent in string. in case pointer p equal null , code snippet have undefined behaviour.
you need change like
if ( p ) *p = '\0'; or
if ( ( p = strchr(sentence,'\n') ) != null ) *p = '\0'; it efficient enough because 1 character searched.
however drawback need additional variable point new line character.
this method
if (fgets(sentence, 11, stdin) != null) token = strtok(sentence, "\n"); semantically not suitable. function strtok used in other context when need split string tokens. , function returns null pointer in case if string contains new line character.
so appropriate method this
if (fgets(sentence, 11, stdin) != null) sentence[strcspn(sentence, "\n")] = 0; because safe , no additional variable required.
as me in c++, use
if ( char *p = strchr( sentence, '\n' ) ) *p = '\0'; and in c, use :)
sentence[strcspn(sentence, "\n")] = '\0';
Comments
Post a Comment