C++题解| #字符串最后一个单词的长度#
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
#include<iostream> #include<string> using namespace std; int main() { string str; getline(cin, str); int pos = str.rfind(" "); int num = str.size() - pos - 1; cout << num << endl; }
主要使用了一个getline()方法,读取了一整行的字符,然后使用字符串的rfind从尾到头检索“ ”空格字符,最后通过计算来获得最后一个单词的长度
华为机试刷题记录 文章被收录于专栏
记录一下手打代码的解题思路方便复习