我正在编写一些函数来处理字符串而不使用<string.h>
,我通过这样做得到字符串的长度:
char *str= "Getting the length of this";
int c;
for (c= 0; str[c]!='\0'; c++);
现在c
是我的字符串的长度,所以它使字符串的工作更容易,但我想知道这是否正确(它可行,但可能不是一个正确的方法来做到这一点)。
答案 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);