题解 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
// 1. 直接定位到字符串的最后结束符 // 2. 从后向前开始遍历,直到遇到空格为止 // 3. 输出最后一个单词的长度
#include <iostream> #include <string> #include <vector> using namespace std; int StrLen(string &str) { int len = str.length(); int index = 0; for (int i = len - 1; i >= 0; i--) { if (str[i] == ' ') { return index; } else { index++; } } return index; } int main() { string str ; getline(cin, str); cout << StrLen(str) << endl; return 0; }
#华为笔试#