请问为什么我这样写得不到正确的字符串长度?
#include <stdio.h>
void len(char *s)
{
int i=0;
// char *p=s;
while (*s!='\n')
{
if((*s>='a'&&*s<='z')||(*s>='A'&&*s<='Z'))
i++;
s++;
}
printf("字符串的长度为:%d\n",i);
}
int main()
{
char str[128];
printf("请输入你的string:");
scanf("%s",str);
len(str);
printf("\n");
return 0;
}
输出会变成这样一个结果:
请输入你的string:I have one apple.
字符串的长度为:63
Press any key to continue
while (*s!='\n')换成while (*s!='\0')
修改见注释,供参考:
#include <stdio.h>
void len(char* s)
{
int i = 0;
// char *p=s;
while (*s != '\0') //while (*s != '\n') 字符串以'\0'作为结束标志
{
//if ((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z'))
//空格等其他字符也是字符串内容,这里不需只判断是否是英文字母。
i++;
s++;
}
printf("字符串的长度为:%d\n", i);
}
int main()
{
char str[128];
printf("请输入你的string:");
scanf("%[^\n]", str);
//scanf("%s", str); scanf()函数以 %s 输入字符串时,遇到空格即认为输入结束。
len(str);
printf("\n");
return 0;
}
s!=‘\n'改成s!='\0'