题目描述:
计算字符串最后一个单词的长度,单词以空格隔开
输入:一行字符串,长度小于128
输出:整数N,最后一个单词的长度
样例
hello
world
5
分析:非常基础的题啦,注意考虑只有一个单词的情况,此时不能以空格判定单词结束
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int lenWord(char str[])
{
int lens=strlen(str),lenw=0;
char *p;
p=str+lens-1;
while(*p!=' '&&p!=str)
{
lenw++;
--p;
}
if(p==str)
lenw=lens;
return lenw;
}
int main()
{
freopen("in.txt","r",stdin);
char s[130]={'\0'};
gets(s);
cout<<lenWord(s)<<endl;
return 0;
}