/*
编码完成下面的处理功能。
函数将字符串中的字符'*'移到串的前部分,前面的非'*'字符后移,但不能改变非'*'字符的先后顺序,函数返回串中字符'*'的数量。
如原始串为:ab**cd**e*12,处理后为*****abcde12
//*/
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
void swap_star(char& a, char& b){
char t;
t = a;
a = b;
b = t;
}
int main()
{
char star[] = "ab**cd**e*12";
cout << " star : " << star << endl;
int sz = sizeof(star);
int starpos = sz - 2;
int nonstar = sz - 2;
int cnt = 0;
while(starpos >= 0 && nonstar >= 0){
while(star[starpos] != '*' && starpos > 0){ //从末位开始查找‘*’的索引
--starpos;
}
if(starpos > 0){ // 计算非‘*’字符的起始索引,与‘*’一样,倒序搜索,因为要求不改变原非‘*’字符的顺序
if(starpos > nonstar){
nonstar = nonstar - 1;
}else{
nonstar = starpos - 1;
}
}else{ // 如果‘*’索引到了 0, 则说明已交换顺序完毕
break;
}
while(star[nonstar] == '*' && nonstar > 0){ // 找到待交换非‘*’字符索引
--nonstar;
}
if(star[nonstar] != '*' && nonstar >= 0){
swap_star(star[starpos],star[nonstar]);
starpos = starpos - 1;
}else{
cnt = starpos + 1; // 交换完毕,‘*’字符的索引是从0开始的最后一个‘*’字符的索引
break;
}
}
cout << "finally : " << star << " star number : " << cnt << endl;
return 0;
}