题目描述
计算字符串最后一个单词的长度,单词以空格隔开。
输入描述:
一行字符串,非空,长度小于5000。
输出描述:
整数N,最后一个单词的长度。
输入例子:
hello world
输出例子:
5
我的直接实现如下:
#include <iostream> #include <string> #include <stdio.h> using namespace std; int calLastWordLength(string str) { int cnt=0; auto it=str.end()-1; while(*it){ if(isspace(*it))break; else{ it--; cnt++; } } return cnt; } int main() { string str; getline(cin,str); cout<<calLastWordLength(str); }
牛客网发现一种使用STL库的简洁方法:int main() { string input; string outStr; while( getline(cin,input)) { auto pos=input.rfind(" ");//逆向查找 返回索引 outStr.assign(input,pos+1,input.size()-pos); /* int cnt=0; for(auto i=pos;i!=input.size()-1;i++) { cnt++; } cout<<cnt<<endl; */ cout<<outStr.size()<<endl; } }
本文介绍了一种计算字符串中最后一个单词长度的方法。利用C++ STL库中的函数,通过逆向查找来确定最后一个单词的位置,并计算其长度。文章提供了一个简洁的实现方案。
259

被折叠的 条评论
为什么被折叠?



