【c++】计算字符串最后一个单词的长度,单词以空格隔开。

牛客网上华为一道笔试题:

第一次刷题,做的很慢,认识到自己的差距。


我的答案:

#include<iostream>
#include<string>
  
using namespace std;
 
 
int main()
{
    string str1;
    string str2;
    int count=0;
    int num = 0;
    //cin >> str1;
    getline(cin, str1);
    //cout << str1<<endl;
    int len = str1.length();
    for (int i = 0; i < len; i++)
    {
        if (str1[i] == ' ')
        {
            count++;
            num = i;
        }
    }
    if (count == 0)
    {
        cout << len<<endl;
    }
    else
    {
        cout << len - num - 1<<endl;
 
    }
    return 0;
 
}

其中遇到的问题:

1、不能用cin>>str1,因为遇到空格自动判断字符串终止,用getline(cin, str1);

2、在for循环中不能用str2[i]=str1[i],因为str2没有事先分配空间,会报运行错误  用str2+=str1[i]

 


看到的别人NB的答案:


#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
getline(cin,str);
int count=0;
int len=str.length();
for(int i=(len-1);i>=0;i--)
{
if(str[i]!=' ')
{
count++;
}
else
{
break;
}
}
cout<<count<<endl;

还需要继续努力啊!!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值