简体   繁体   English

计算C中字符串的长度

[英]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. 我正在使用fgets读取字符串。 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 . 无需担心fgets()并删除尾随\\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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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