This solution uses all inbuilt methods of cpp to make life simple.
First being strtok which takes char* as input and splits it with the delimiter we provide Check the Method here
Next we need to convert our string to char* so we use .c_str() function. However, it porivdes const char* hence we use strdup().
class Solution {
public:
int lengthOfLastWord(string s) {
int ans = 0;
char *token = strtok(strdup(s.c_str()), " "); //Converting the string to char* and then making it mutable
while(token!=NULL)
{
string str(token); //Converting char* to String
ans = str.size();
token=strtok(NULL, " ");
}
return ans;
}
};