通过最终的NUL元素获取字符串的长度

时间:2017-11-05 11:22:10

标签: c string

我正在编写一些函数来处理字符串而不使用<string.h>,我通过这样做得到字符串的长度:

char *str= "Getting the length of this";
int c;
for (c= 0; str[c]!='\0'; c++);

现在c是我的字符串的长度,所以它使字符串的工作更容易,但我想知道这是否正确(它可行,但可能不是一个正确的方法来做到这一点)。

1 个答案:

答案 0 :(得分:4)

  

......我想知道这是否正确

是的,这是正确的。

为了便于阅读,我更愿意:

char *str= "Getting the length of this";
int c = 0;
while(str[c]) c++;

但这只是一个品味问题。

请注意,使用int表示字符串长度并不常见。 strlen函数返回size_t所以为了模仿库函数,你还应该使用size_t赞:

size_t my_strlen(const char* s)
{
    size_t c = 0;
    while(s[c]) c++;
    return c;
}


char *str= "Getting the length of this";
size_t c = my_strlen(str);