---
# System prepended metadata

title: Question 58. Length of Last Word
tags: [leetcode]

---

###### tags: `leetcode`
# Question 58. Length of Last Word
### Description:
Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

A word is a maximal substring consisting of non-space characters only.
### Solution:
What I recorded here is my first idea after i read this question. It's strtok with c++. It didn't work but the following is the method to tokenized string in cpp.
```cpp=
#include <sstream>
using namespace std;
//s = "abc,def,ghi"
void token(string s){
    stringstream ss(s);
    string subs;
    while(getline(ss, subs, ',')){
        cout<<subs<<endl;
    }
}
```
```
abc
def
ghi
```
### AC code
```cpp=
#include <iostream>
#include <string>
class Solution {
public:
    int lengthOfLastWord(string s) {
        int ans = 0;
        int l = s.length()-1;
        for(l ; l >= 0 ; l--){
            if(s[l]!=' '){
                ans++;
            }
            else if(ans!=0)
                break;
        }
        return ans;
    }
};
```