【華爲機試在線訓練】字符串最後一個單詞的長度

題目

計算字符串最後一個單詞的長度,單詞以空格隔開。
輸入描述:

一行字符串,非空,長度小於5000。

輸出描述:

整數N,最後一個單詞的長度。

示例1

輸入
hello world

輸出
5

思路

使用 getline 的 C++ 函數,此函數可讀取整行,包括前導和嵌入的空格,並將其存儲在字符串對象中;
然後從尾部遍歷字符串,當爲空格時,結束。

C++代碼

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str;
    while(getline(cin, str))
    {
        int count = 0;
        int n = str.length();
        for(int i = n - 1; i >= 0; i--)
        {
            if(' ' == str[i])
            {
                break;
            }
            count++;
        }
        cout << count << endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章