HJ1 字符串最后一个单词的长度(C++)- 简单、字符串

HJ1 字符串最后一个单词的长度(C++)- 简单、字符串,第1张

题目链接:https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da?tpId=37&tqId=21224&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
题目如下:

#include 
using namespace std;

int main(){
    string str="";
    
    while(getline(cin,str)){//每次获得一行输入,无限循环
        int pos=str.size()-1;
        int res=0;
        
        while(pos>=0&&str[pos]==' ') pos--;//清除末尾为0的情况
    
        for(;pos>=0;pos--){//开始正式计数
            if(str[pos]!=' ') res++;
            else break;
        }
    
        cout<<res<<endl;
    }
    
    return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1498489.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-25
下一篇2022-06-25

发表评论

登录后才能评论

评论列表(0条)

    保存