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;
}
为什么这不能按预期工作?我只想找到一个字符串的长度。
最佳答案
来自对另一个答案的评论:
I am using fgets to read in a string. and i have checked to make sure that the string that was typed was stored correclty
在这种情况下,存储了一个尾随换行符,因此您的函数会计算
strlength("hello\n")
代码是正确的,您只是没有将您认为应该传递的输入传递给它。
关于C计算字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14540681/