字符串中的单词逆序输出

1、题目描述

给定一个整数N,输入N行字符串,并依次逆序输出每个字符串中的单词。例如:

输入:

4
boy am I
football playing like I
theatre the to went I week Last
question a that's be, to not or be to


输出:

I am boy
I like playing football
Last week I  went to  the theatre 
to be or  not to be, that's a question  


2、实现代码

//注意:输入多行字符串的实现

#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
using namespace std;
int main(){
	string s;
	int n,i,j,k,len;
	while(cin>>n){
		char ch=getchar();//这里要用一个字符来接收换行符,切记!!
    	        string str[n];//定义string类对象数组!
    	        for(i=0;i<n;i++){
     		    getline(cin,str[i]);
                    len=str[i].size();
                    j=len-1;
          	    for(int ii=len-1;ii>=0;ii--){
   	     	        if(str[i][ii]==' '){
		    	    j=ii;
	                    for(k=j+1;str[i][k]!=' '&&k<len;k++)
	    	                 cout<<str[i][k];
	            	    cout<<' ';
	                }
                     }
                    if(j!=len-1){
            	        for(int ii=0;ii<j;ii++)
	                   cout<<str[i][ii];
	                cout<<endl;
                    }
                    else{
                 	  for(int ii=0;ii<=j;ii++)
                	      cout<<str[i][ii];
                 	  cout<<endl;
                    }
       	
	         }
	}
	
	
		
	return 0;
}
运行结果:



猜你喜欢

转载自blog.csdn.net/cnd2449294059/article/details/77802326