1. 程式人生 > >華為oj:計算字串最後一個單詞的長度,單詞用空格隔開

華為oj:計算字串最後一個單詞的長度,單詞用空格隔開

/*
描述
計算字串最後一個單詞的長度,單詞以空格隔開。
知識點 字串,迴圈
執行時間限制 0M
記憶體限制 0
輸入 一行字串,長度小於128。
輸出 整數N,最後一個單詞的長度。
樣例輸入 hello world
樣例輸出 5*/

#include<iostream>
#include<string>
using namespace std;

int main(){
    string str;
    getline(cin, str);
    int length_word = 0;            // 單詞長度    
    int
spaceSum = 0; // 非字母的字元 for (int i = str.size() - 1; i >= 0; --i){ if ((str[i] == ' ') || (!isalpha(str[i]))) { spaceSum++; } else break; } for (int i = str.size() - spaceSum - 1; i >= 0; --i){ if ((str[i] == ' ') || (!isalpha
(str[i]))){ break; } else{ length_word++; } } cout << length_word << endl; return 0; }
引用他人
#include <string>  
#include <algorithm>  
#include <iostream>  
using namespace std;  

int main(void)  
{  
    string
str; getline(cin,str); int pos = str.rfind(" "); cout << str.substr(pos+1).length() << endl; system("pause"); return 0; }