gpt4 book ai didi

c - 返回字符串的长度

转载 作者:行者123 更新时间:2023-11-30 20:55:27 25 4
gpt4 key购买 nike

我看到有人发布了这个返回字符串长度的函数。有人可以向我逐行解释会发生什么吗,因为我不明白 *s 指针发生了什么以及它如何能够逐一遍历字符串并计算字符串中的字符数。这个函数来自FreeBSD

size_t
strlen(const char *str)
{
const char *s;
for (s = str; *s; ++s);
return(s - str);
}

最佳答案

size_t
strlen(const char *str)
{
const char *s; // init pointer
for (s = str; *s; ++s); // set pointer to beginning of str, and increment pointer until
// you reach '\0', which is the end of the string
return(s - str); // compute the distance between end and beginning of string
// (s points to end of string, str points to beginning of string)
}

关于c - 返回字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33046329/

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