C语言三种方法实现字符串右旋

方法一:三步旋转法

#define _CRT_SECURE_NO_WARNINGS 1  
#include  
#include  
#include  
#include  

//三步旋转法
void filp(char *left, char *right)
{
	assert(left);
	assert(right);

	while (left


方法二:移项法

#define _CRT_SECURE_NO_WARNINGS 1  
#include  
#include  
#include  
#include  

//移项法
void RightHand(char *str, int len)
{
	assert(str);

	int i = 0;
	int num = 0;
	char temp = 0;
	for (i = 0; i < len; i++)
	{
		num = strlen(str);
		num--;
		temp = str[num];
		while (num>0)
		{
			str[num] = str[num - 1];
			num--;
		}
		str[num] = temp;
	}

}

int main()
{
	char a[] = "abcdefj";
	RightHand(a, 2);
	printf("%s\n", a);
	system("pause");
	return 0;
}

C语言三种方法实现字符串右旋_第1张图片



方法三:进行开辟双倍字符串空间
#define _CRT_SECURE_NO_WARNINGS 1  
#include  
#include  
#include  
#include  



//方法三:进行开辟双倍字符串空间
void RightHand(char *str, int len)
{
	assert(str);
	assert(len > 0);
	char *Buff = NULL;
	char *start_Buff = Buff;
	int num = strlen(str);
	Buff = (char*)malloc(2 * num + 1);
	strcpy(Buff, str);
	strcat(Buff, str);
	strncpy(str, Buff + num-len, num);
}
int main()
{
	char a[] = "abcdefj";
	RightHand(a, 2);
	printf("%s\n", a);
	system("pause");
	return 0;
}




你可能感兴趣的:(c语言)