第一道循环的题
思路是将字符串读入,然后逆序排列,将字符串流打散,保留第一个单词,再逆序就是原字符串的最后一个单词。
实现的思路有些繁琐,代码如下:
</pre><pre name="code" class="cpp">#include<string>
#include<vector>
#include<iostream>
#include<sstream>
using namespace std;
void main(){
string str;
getline(cin,str);//读入字符串
reverse(str.begin(), str.end());//字符串逆序
string last;//定义存储最后单词
stringstream ss(str);//字符串流
vector<string>token;//将字符串打散存入向量
while (ss >> last){
token.push_back(last);
}
cout << token[0].length();//这里用size()也是可以的
//string lastword;
//lastword = token[0];
//reverse(lastword.begin(), lastword.end());
//cout << lastword;
system("pause");
return;
}
reverse() stringstream istringstream ostringstream find_last_of.
下面贴几个写的比较好的代码
- #include <iostream>
- #include <string.h>
- #include <sstream>
- using namespace std;
- int main()
- {
- string input,cur,pre;
- getline(cin,input);
- istringstream line(input);
- while(line>>cur)
- {
- pre=cur;
- }
- cout<<pre.length()<<endl;
- return 0;
- }
- #include "iostream"
- #include"string"
- using namespace std;
- int main()
- {
- string a;
- getline(cin,a);
- cout<<a.substr(a.find_last_of(' ')+1).size();
- return 0;
- }
- #include <iostream>
- #include <string>
- using namespace std;
- int main()
- {
- string Str;
- int len, pos;
- getline(cin, Str);
- len = Str.length();
- pos = Str.find_last_of(' ');
- cout << len-pos-1 << endl;
- return 0;
- }