字符串倒着复制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SYaoJun/article/details/86565401

一个字符串只包含星号和数字,请把它的*都放在开头
方法1:快排的partition ——数字相对顺序发生改变

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main(){
	char str[]="*01*2*4";
	int len=strlen(str);
	for(int i=0,j=0;j<len;j++){
		if(str[j]=='*') {
			swap(str[i++],str[j]);
		}
	}
	puts(str);
}

方法2:倒着复制 ——数字相对顺序不发生改变

#include<cstdio>
#include<cstring>
#include<cctype>
int main(){
	char str[]="*01*2*4";
	int len=strlen(str);
	int j=len-1;
	for(int i=len-1;i >=0;--i){
		if(isdigit(str[i]))  
				str[j--]=str[i];
	}
	for(;j>=0;j--){
		str[j]='*';
	}
	puts(str);
}

猜你喜欢

转载自blog.csdn.net/SYaoJun/article/details/86565401