题解 | 字符串最后一个单词的长度
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s);
auto pos = s.find_last_of(' ');
pos = (pos == string::npos)? -1 : pos;
cout << s.size() - pos -1 << endl;
}
主要是运用字符串函数强大的功能,减少代码量。
注意排除只输入一个单词的情况,该情况无空格