首页 > 代码库 > 字符串移位

字符串移位

字符串循环移位:假设有一串字符串a,b,c,d,e,f,g,h,向左循环移位2为,得c,d,e,f,g,h,a,b。

#include<iostream>
using namespace std;

void reverse(char* a, int start, int len){
	int count = 0;

	for(int i = start, j = start + len -1; ; ++i, --j){
		if((++count) <= len/2){
			a[i] = a[i] + a[j];
			a[j] = a[i] - a[j];
			a[i] = a[i] - a[j];
		}else{
			break;
		}
	}
}

void transposition(char* a, int n, int len){
	reverse(a,0,len);
	reverse(a,0,len-n);
	reverse(a,len-n,n);
}



void main(){
	char a[] = {'a','b','c','d','e','f','g','h'};
	int len = sizeof(a);
	transposition(a,9%len,len);
	for(int i = 0; i < len; ++i){
		cout<<a[i]<<" ";
	}
	cout<<endl;
}
结果:



字符串移位