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;
}