2038. String Reversion

2038. String Reversion

Description

 Given a valid identifier in C programs, please write a program to reverse it by respectively reversing two parts separated by ‘_’.

Input

 The first line is an integer m, indicating the number of test cases.
Then there are m lines and each line contains a string. A string will contain no more than 100 characters and there is one or less ‘_’.

Output

 For each test case, print out the string reversed.

Sample Input

3
John_Smith
int_45
_me

Sample Output

nhoJ_htimS
tni_54
_em

Problem Source

10级CS程序设计


原谅我做的时候没学类,麻烦到死

#include <iostream>
#include <string>
using namespace std;

int main()
{
	int m;
	cin>>m;
	while(m--)
	{
		string str,left,right;
		cin>>str;
		int count;
		bool bo=true;
		//cout<<str.length()<<endl;
		for(int i=0;i<str.length();i++)
		{
			if(str[i]=='_')
			{
				bo=false;
				break;
			}
		}
		if(bo)
		{
			if(str.length()==2)
				cout<<str[1]<<str[0]<<endl;
			else
			{
				for(int i=0;i<=str.length()/2;i++)
				{
					int temp=str[i];
					str[i]=str[str.length()-1-i];
					str[str.length()-1-i]=temp;
				}
				if(str.length()%2==0)
				{
					int temp=str[str.length()/2-1];
					str[str.length()/2-1]=str[str.length()/2];
					str[str.length()/2]=temp;
				}
				cout<<str<<endl;
			}
			continue;
		}
		for(count=0 ;str[count]!='_';count++){}
		//cout<<count<<endl;
		if(str[0]=='_')
		{
			cout<<'_';
			for(int i=str.length()-1;i>=1;i--)
				cout<<str[i];
			cout<<endl;
			continue;
		}
		if(count==str.length()-1)
		{
			for(int i=str.length()-2;i>=0;i--)
				cout<<str[i];
			cout<<'_'<<endl;
			continue;
		}
		left=str.substr(0,count);
		if(left.length()==2)
		{
			int temp=left[0];
			left[0]=left[1];
			left[1]=temp;
		}
		else
		{
			for(int i=0;i<=left.length()/2;i++)
			{
				int temp=left[i];
				left[i]=left[left.length()-1-i];
				left[left.length()-1-i]=temp;
			}
			if(left.length()%2==0)
			{
				int temp=left[left.length()/2-1];
				left[left.length()/2-1]=left[left.length()/2];
				left[left.length()/2]=temp;
			}
		}
		right=str.substr(count+1,str.length()-1-count);
		if(right.length()==2)
		{
			int temp=right[0];
			right[0]=right[1];
			right[1]=temp;
		}
		else
		{
			for(int i=0;i<=right.length()/2;i++)
			{
				int temp=right[i];
				right[i]=right[right.length()-1-i];
				right[right.length()-1-i]=temp;
			}
			if(right.length()%2==0)
			{
				int temp=right[right.length()/2-1];
				right[right.length()/2-1]=right[right.length()/2];
				right[right.length()/2]=temp;
			}
		}
		cout<<left<<'_'<<right<<endl;
	}
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值