字符串最后一个单词的长度

第一道循环的题

思路是将字符串读入,然后逆序排列,将字符串流打散,保留第一个单词,再逆序就是原字符串的最后一个单词。

实现的思路有些繁琐,代码如下:

</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.


下面贴几个写的比较好的代码

  1. #include <iostream>        
  2. #include <string.h>     
  3. #include <sstream>     
  4. using namespace std;        
  5.   
  6. int main()        
  7. {        
  8.   
  9.     string input,cur,pre;  
  10.     getline(cin,input);  
  11.     istringstream line(input);  
  12.         while(line>>cur)  
  13.             {  
  14.             pre=cur;  
  15.         }  
  16.         cout<<pre.length()<<endl;  
  17.   
  18.     return 0;        
  19.   
  20. }  



  1. #include "iostream"  
  2. #include"string"  
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.   
  8.     string a;  
  9.     getline(cin,a);   
  10.   
  11.     cout<<a.substr(a.find_last_of(' ')+1).size();    
  12.   
  13.         return 0;  
  14.   
  15.       
  16. }  

  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     string Str;  
  8.     int len, pos;  
  9.     getline(cin, Str);  
  10.     len = Str.length();  
  11.     pos = Str.find_last_of(' ');  
  12.     cout << len-pos-1 << endl;  
  13.     return 0;  
  14. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值