简体   繁体   中英

Calculating length of a string in C

int strlength(const char *myStr){
    //variable used for str length counter
    int strlength = 0;
    //loop through string until end is reached. Each iteration adds one to the string length
        while (myStr[strlength] != '\0'){
            putchar(myStr[strlength]);
            strlength++;
        }

    return strlength;
}

Why will this not work as intended? I just want to find the length of a string.

From a comment on another answer:

I am using fgets to read in a string. and i have checked to make sure that the string that was typed was stored correclty

In that case, there is a trailing newline stored, so your function computes

strlength("hello\n")

The code is correct, you just didn't pass it the input you believed to pass.

More reliable version:

size_t strlength(const char * myStr)
{
    return strlen(myStr);
}

You can try this also:-

int string_length(char *s)
{
   int c = 0;

   while(*(s+c))
      c++;

   return c;
}

No need to worry about fgets() and removing the trailing \\n .

while (myStr[strlength] != '\0'){
            putchar(myStr[strlength]);
            strlength++; //When mysStr[strlength] == \0, this line would have already incremented by 1
}

Quick fix:

return (strlength-1);//This will return correct value.

A more better approach:

int strlen(const char *s)
{
   char *str=s;
   while(*str)
   {
      str++;
   }
   return (s-str);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM