字符串移动

/*
编码完成下面的处理功能。
      函数将字符串中的字符'*'移到串的前部分,前面的非'*'字符后移,但不能改变非'*'字符的先后顺序,函数返回串中字符'*'的数量。
      如原始串为: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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值