例如:"hello world"
返回 5;
方法一:
基於STL
int LastWordLen1(const char* s)
{
if (NULL == s)
return 0;
string str(s);
size_t start = str.find_last_of(' ');//返回' '的位置
return str.size() - start - 1;
}
方法二:
從前向後遍歷,用變量 len 記錄單詞的長度,如果此單詞不是最後一個單詞,更新 len 的長度,即len=0
int LastWordLen(const char* s)
{
if (NULL == s)
return 0;
int len = 0;
while (*s != '\0')
{
len++;
if (*s == ' ')
len = 0;
s++;
}
return len;
}