求字符串中最後一個單詞的長度

例如:"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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章