gpt4 book ai didi

c - 通过最后一个 NUL 元素获取字符串的长度

转载 作者:行者123 更新时间:2023-11-30 18:28:26 26 4
gpt4 key购买 nike

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

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

现在c是我的字符串的长度,因此它使处理字符串变得更加容易,但我想知道这是否正确(它可以工作,但可能不是执行此操作的正确方法)。

最佳答案

... i wonder if this is correct

是的,这是正确的。

为了可读性,我更喜欢:

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);

关于c - 通过最后一个 NUL 元素获取字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47120976/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com