题目描述
计算字符串最后一个单词的长度,单词以空格隔开。
输入描述:
一行字符串,非空,长度小于5000。
输出描述:
整数N,最后一个单词的长度。
示例1
输入: hello world
输出: 5
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
//定义在一个std的namespace
using namespace std;
//定义方法
int lastWordLength(char * str)
{
if(0==str)
return 0;
char * p = str;
char * pLast = NULL;
while(*p)
{
pLast = p;
p++;
}
int nRe = 0;
while(*pLast !=32&& pLast != str)
{
nRe++;
pLast--;
}
return (pLast ==str) ? nRe+1 : nRe;
}
//主函数
int main()
{
char szBuf[5012] = {0};
while (cin.getline(szBuf, 5000))
{
int num =lastWordLength(szBuf);
printf("%d\n", num);
}
return 0;
}