The above code is incorrect, modify the answer with the code as follows:
First uses scanf() to get the string, which ends at the first whitespace character, so you enter a string with a space. Getting the input is an error, and you can use gets() instead;
This code makes an error judgment if the last word is followed by a space. It also makes an error judgment if it is a non-alphabetic character. Increase the error judgment when calculating the length from back to back, start with the first alphabetic character and end with the first non-alphabetic character.
https://www.runoob.com/cprogramming/c-function-isalpha.html
https://baike.baidu.com/item/gets/787649?fr=aladdin
https://baike.baidu.com/item/scanf/10773316?fr=aladdin
#include
#include
int ln(char *s)
{
int i=0;
char * oriS=s;
while(*s!='\0') // 让指针指向字符串最后的空字符
s++;
s--; // 让指针指向空字符前一个字符位置
//printf("before,s=%s\n",s);
// https://www.runoob.com/cprogramming/c-function-isalpha.html
while(isalpha(*s)==0&&s>=oriS) // 如果当前字符不是字母并且仍在字符串内,则指针往前移动一个位置,直到遇到第一个字母
{
s--;
}
while(isalpha(*s)!=0&&s>=oriS){ // 如果当前字符是字母,且仍在字符串内,则进行单词长度计算。直到遇到第一个非字母
i++;
s--;
}
// printf("end,s=%d\n",s);
return i;
}
int main()
{
char a[1024];
// https://baike.baidu.com/item/scanf/10773316?fr=aladdin
// scanf("%s",a);
// https://baike.baidu.com/item/gets/787649?fr=aladdin
gets(a);
//printf("a=%s\n",a);
int l=ln(a);
printf("%d\n",l);
return 0;
}
