题解 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
#include <iostream> #include <string> using namespace std; int main() { string str; getline(cin,str); int found = str.find_last_of(" "); string last_word = str.substr(found+1); int len = last_word.size(); cout << len << endl; return 0; } // 64 位输出请用 printf("%lld")
string库函数解法:
在C++中,find_last_of()函数是一个字符串函数,它可以在给定的字符串中搜索最后一个与指定字符序列中任何一个字符相匹配的字符,并返回该字符的位置。
substr()是一个预定义函数,主要功能是复制子字符串。它要求从指定位置开始,并具有指定的长度。substr()函数是C++头文件string中的函数。substr(pos,len)返回从pos开始,长度为len的字串,时间复杂度为O(len)。1