最后一个单词的长度

来源:@计蒜客—最后一个单词的长度

题目:

给定由大写,小写字母和空格组成的字符串,返回最后一个单词的长度。如果输入中不存在单词,返回0。

输入格式:
输入仅一行,为字符串 ss(长度不超过 1000),以回车结尾。

输出格式:
输出 ss 中最后一个单词的长度。

解析:

 1.要求打印最后一个单词,当输入字符串的末尾为空格时,需要忽略掉。

1
2
Input: "abc abc  "
Output: 3

 2.要求当输入为空时,返回0。“返回0”意为打印字符0并返回,而非简单“return 0”。

C++知识:

 字符串的输入:题目要求输入为一行,以回车结束,所以使用C++中的getline()函数,函数原型为:

1
istream& getline(istream &is, string &str, char delim);

 第一个参数为承担读入操作的输入流,可以是cin、ifstream等;第二个参数为string型参数,读入的字符串就存于该类型变量中;第三个参数为结束标识符,缺省第三个参数时,参数值默认为字符’\0’,在读入过程中一旦遇到此字符就结束字符串输入,将此字符前的字符存入指定位置而丢弃后续字符。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "iostream"
#include "stdlib.h"
#include "string"
using namespace std;

int main(int argc, char const *argv[])
{
string input;
getline(cin, input);

if(input.empty()){
cout << "0" << endl;
return 0;
}
int index = input.length()-1, len = 0;
while(input[index] == ' ') index--;
while(input[index] != ' '){
len++;
index--;
}
cout << len << endl;

system("pause");
return 0;
}

转载请注明来源:©Tinshine