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

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
void Left_Spin(char arr[], int len, int k)
{
	assert(arr);
	assert(len > 0);
	int i = 0;
	int temp = 0;
	temp = arr[0];
	int n = 0;
	for (n = 0; n < k; n++)
	{
		for (i = 0; i < len; i++)
		{
			arr[i] = arr[i + 1];
		}
		arr[len-1] = temp;
	}
}
int main()
{
	int num = 0;
	char array[] = "abcdef";
	int len = strlen(array);
	printf("Please  Enter number:");
	scanf("%d", &num);
	printf("Before:%s\n", array);
	Left_Spin(array,len,num);
	printf("After:%s\n", array);
	system("pause");
	return 0;

}

//方法二:把字符串分成两部分,
//一部分为:从字符串的开始-左旋的次数-1位置的字符串。
//另一部分为:左旋的次数-1位置的字符串到结尾的位的位置
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
void Swap(char *x, char *y)
{
	*x ^= *y;
	*y ^= *x;
	*x ^= *y;
}
void Left_Spin(char arr[], int len, int k)
{
   assert(arr);
   assert(len > 0);
	char *start = arr;
	char *middle = arr + (k - 1);
	char *end = arr + len - 1;
	while (start < middle)
	{
		Swap(start, middle);
		start++;
		middle--;
	}
	start = arr;
	middle = arr + (k - 1);
	while (middle + 1 < end)
	{
		Swap(middle + 1, end);
		middle++;
		end--;
	}
	end = arr + len - 1;
	while (start < end)
	{
		Swap(start, end);
		start++;
		end--;
	}
}
int main()
{
	int num = 0;
	char array[] = "abcdef";
	int len = strlen(array);
	printf("Please enter number:\n");
	scanf("%d", &num);
	num %= len;
	printf("Before:%s\n", array);
	Left_Spin(array, len, num);
	printf("After:%s", array);
	system("pause");
	return 0;

}


//方法三:进行开辟双倍字符串空间
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
void Left_Spin(char arr[], int len, int k)
{
	assert(arr);
	assert(len > 0);
	char *Buff=NULL;
	char *start_Buff = Buff;
	Buff = (char*)malloc(2 * len+1);
	strcpy(Buff, arr);
	strcat(Buff, arr);
	strncpy(arr, Buff + k,len);
}
int main()
{
	int num = 0;
	char array[] = "abcdef";
	int len = strlen(array);
	printf("Please enter number:\n");
	scanf("%d", &num);
	num %= len;
	printf("Before:%s\n", array);
	Left_Spin(array, len, num);
	printf("After:%s", array);
	system("pause");
	return 0;

}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值