牛客网上华为一道笔试题:
第一次刷题,做的很慢,认识到自己的差距。
我的答案:
#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;
还需要继续努力啊!!!