您的位置:首页 > 其它

[华为机试练习题]19.字符串最后一个单词的长度

2015-06-30 15:11 211 查看
题目



代码

/*---------------------------------------
*   日期:2015-06-30
*   作者:SJF0115
*   题目:字符串最后一个单词的长度
*   来源:华为上机
-----------------------------------------*/
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;

int LastWordLength(string str){
    int size = str.size();
    if(size == 0){
        return 0;
    }//if
    // 去除后导0
    int end = size - 1;
    while(end >= 0 && str[end] == ' '){
        --end;
    }//while
    int len = 0;
    while(end >= 0 && str[end] != ' '){
        ++len;
        --end;
    }//while
    return len;
}

int main(){
    string str;
    //freopen("C:\\Users\\Administrator\\Desktop\\c++.txt","r",stdin);
    while(getline(cin,str)){
        cout<<LastWordLength(str)<<endl;
    }//while
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: