题目
把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间。
解题之法
#include <iostream>
#include <string.h>
using namespace std;
int main(){
string s;
while(cin >> s){
if(s.length() >= 1 && s.length() <= 1000){
for(int i = 0; i < s.length(); i++)
if(s[i] >= 'a' && s[i] <= 'z')
cout << s[i];
for(int i = 0; i < s.length(); i++)
if(s[i] <= 'Z' && s[i] >= 'A')
cout << s[i];
cout << endl;//
}
}
return 0;
}
分析
上述解法是取巧,只为输出字符串,如果要想交换大小写位置,给出下面这种解法:
#include<iostream>
#include<string>
using namespace std;
bool isCap(char c)
{
if (c >= 'A' && c <= 'Z')
return true;
else
return false;
}
void mSwap(char &a, char &b)
{
if (a != b)
{
a ^= b;
b ^= a;
a ^= b;
}
}
int main()
{
string s;
while (cin >> s)
{
int len = s.size();
int end = len;
for (int i = 0; i<end; ++i)
{
if (isCap(s[i]))
{
int j = i;
for (; j<len- 1; ++j)
mSwap(s[j], s[j + 1]);
--end;
--i;
}
}
cout << s <<endl;
}
return 0;
}