牛客网–华为机试在线训练1:字符串最后一个单词的长度
题目地址:
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da?tpId=37&tqId=21224&tPage=1&rp=&ru=/ta/huawei&qru=/ta/huawei/question-ranking
题目描述
计算字符串最后一个单词的长度,单词以空格隔开。
输入描述:
一行字符串,非空,长度小于5000。
输出描述:
整数N,最后一个单词的长度。
示例1
输入
hello world
输出
5
我的答案:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
string str;
while(getline(cin,str)){ //若以cin输入字符串,遇到空格会结束;geiline则能输入整行,遇到换行符结束
str.erase(0,str.find_first_not_of(" "));//这两行作用是去除首尾空格
str.erase(str.find_last_not_of(" ") + 1);
auto iter1 = str.find_last_of(' ');//原来这类函数返回的是整数或string::npos
if(iter1 == string::npos)
cout << str.size() << endl;
else
cout << str.size() - 1- iter1 << endl;
}
return 0;
}