题目:小Q最近遇到了一个难题:把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间。
你能帮帮小Q吗?
输入描述:
输入数据有多组,每组包含一个字符串s,且保证:1<=s.length<=1000.
输出描述:
对于每组数据,输出移位后的字符串。
输入例子1:
AkleBiCeilD
输出例子1:
kleieilABCD
本题比较水,很多解法,以下是一些网上的方法的总结
解法一:从前到后扫描字符,如果是大写,就拿出来,放在字符串的最后,剩下的依次往前移动(这应该是最容易想到的)
#include <iostream>
using namespace std;
int main()
{
string str;
while(cin>>str){
char p;
int index=0;
int t;
int len_str = str.length();
while(len_str--){
//要检查多少个字
if(str[index]>='A' && str[index]<='Z'){
//检查如果是大写,就依次向前移动
t = index;
p = str[index];
while(index<str.length()-1){
str[index]=str[index+1];
index++;
}
str[index]=p;
index=t;
index--;
}
index++;
}
cout<<str<<endl;//不加<<endl是错的。。。
}
return 0;
}
解法二:将大小写分别放在两个数组后面,然后,拼接这两个数组。
#include <iostream>
using namespace std;
int main()
{
string str;
while(cin>>str){
string str1 = "";
string str2 = "";
for (int i = 0; i < str.length(); ++i) {
if(str[i]>='A'&&str[i]<='Z') str1+=str[i];
else str2 += str[i];
}
str = str2+str1;
cout<<str<<endl;
}
return 0;
}
解法三:使用stable_partition函数(大神。。)
注:这个函数的作用是,用一个判断函数,如果这个判断函数为真,就将相应的char提前。
#include <iostream>
#include <algorithm>
using namespace std;
bool lower(char c) {
return c>='a';
}
int main()
{
string str;
while(cin>>str){
stable_partition(str.begin(), str.end(), lower);
cout<<str<<endl;
}
return 0;
}
解法四、大小写分开直接输出。。。。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string str;
while(cin>>str){
for (int i = 0; i < str.length(); ++i) {
if (str[i]>='a'&&str[i]<='z') cout<<str[i];
}
for (int j = 0; j < str.length(); ++j) {
if(str[j]>='A'&&str[j]<='Z') cout<<str[j];
}
cout<<endl;
}
return 0;
}