一点也不基础编程题目集 7-26 单词长度 (C++)

这题我也必须写一篇博客纪念自己耗了这么长时间…

本来我想着c语言编程题目集用c++还不是随便写么,这又是一道简单的模拟题嘛!

#include <iostream>
using namespace std;
int main()
{
    int cnt=0;
    string s;
    while(1){
        cin>>s;
        int l=s.length();
        if(cnt++) cout<<' ';
        if(s[l-1]=='.'){
            if(l>1) cout<<l-1;//如果不是空句子
            break;
        }
        else cout<<l;
    }
}

然后最后一个测试点格式错误
问了老师才知道:他说以 . 结束但没说是几个 .

比如:
It’s great to see you here… (多个.)
It’s great to see you here … (多个.且与前面单词有空格)

这时候cin的弊端就出来了… (想用cin偷个懒太难了呜…)

最后一个测试点应该是第二种情况
但其实第一种也过不了(我太菜了.jpg)

考虑两种情况后:

#include <iostream>
using namespace std;
int main(){
    int cnt=0;
    string s;
    while(1){
        cin>>s;
        if(s[0]=='.') break;//第二种情况
        int l=s.length();
        if(cnt++) cout<<' ';
        if(s[l-1]=='.'){
            while(s[l-1]=='.') l--;//第一种情况以及空句子
            if(l) cout<<l;
            break;
        }
        else cout<<l;
    }
}

优化后:

#include <iostream>
using namespace std;
int main(){
    int cnt=0;
    string s;
    while(cin>>s){
        if(s[0]=='.') break;//.与单词不相连的情况,这里也可以用continue,但是会多进行一次cin操作
        int l=s.length();
        while(s[l-1]=='.') l--;//.与单词相连,减去所有.的个数后输出余下长度
        if(cnt++) cout<<' ';
        cout<<l;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值