length-of-last-word.cpp (650B)
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 6 // Speed Memory 7 //Total 0ms 6.5MB 8 //Beats 100% 92.69% 9 // 10 11 12 13 14 int lengthOfLastWord(string s) { 15 int len = 0; 16 17 //Trim from the end of the string any white space 18 while(s[s.size() - 1] == ' '){ 19 s.pop_back(); 20 } 21 for(int i = s.size() - 1; i >= 0 ; --i){ 22 23 if(s[i] != ' ' ){ 24 len += 1; 25 } 26 else{ 27 return len; 28 } 29 } 30 31 return len; 32 } 33 34 35 36 37 int main(){ 38 cout << "Type words to find length of last word in list: "; 39 string word = ""; 40 cin >> word; 41 cout << lengthOfLastWord(word) << endl; 42 }