其他分享
首页 > 其他分享> > C语言--字符串左旋

C语言--字符串左旋

作者:互联网

C语言–字符串左旋

字符串左旋:假设一个字符串ABCDEF,左旋三个字符变为了DEFABC

这里列出来两种实现方式

#include <stdio.h>

void string_left_rotate(char* arr, int size, int n)
{
	for (int i = 0; i < n; i++)
	{
		char temp = *arr;
		for (int j = 0; j < size -1; j++)
		{
			*(arr + j) = *(arr + j + 1);
		}
		*(arr + size - 1) = temp;
	}
}
int main()
{
	char arr[20] = "ABCDEF";
	int size = strlen(arr);
	int n = 3;
	string_left_rotate(arr, size, n);
	printf("%s\n", arr);
	return 0;
}
#include <stdio.h>
#include <string.h>
#include <assert.h>

void reverse(char* left, char* right)
{
	assert(left);
	assert(right);
	while (left < right)
	{
		char temp = *left;
		*left = *right;
		*right = temp;
		left++;
		right--;
	}
}
void string_left_rotate2(char* arr, int size, int n)
{
	reverse(arr, arr + n - 1);
	reverse(arr + n, arr + size - 1);
	reverse(arr, arr + size - 1);
}
int main()
{
	char arr[20] = "ABCDEF";
	int size = strlen(arr);
	int n = 3;
	string_left_rotate2(arr, size, n);
	printf("%s\n", arr);
	return 0;
}

标签:arr,right,--,C语言,char,int,left,左旋,size
来源: https://blog.csdn.net/qq_46480020/article/details/121723944