字符串的左旋和右旋

实现一个函数,可以左旋字符串中的k个字符。

ABCD左旋一个字符的到BCDA

ABCD左旋两个字符的到CDAB

#include<stdio.h>
#include<string.h>
void reverse(char arr[], int s, int e)
{
   while(s<e)
   {
      char tmp;
		  tmp = arr[s];
	       arr[s] = arr[e];
		   arr[e] = tmp;
		   s++;
		   e--;
   }
}



int main()
{
	char p[] = "ABCDEF"; 
	//左旋两位
	reverse(p, 0, strlen(p)-1);   //整体翻转  FEDCBA
	reverse(p, 0, strlen(p)-1-2);   //F到C翻转  CDEFBA
	reverse(p, strlen(p)-1-1, strlen(p)-1);   //B到A翻转 CDEFAB
	//右旋两位
	//reverse(p, 0, strlen(p)-1);   //整体翻转  FEDCBA
	//reverse(p, 0, 1);   //F到E翻转  EFDCBA
	//reverse(p, 2, strlen(p)-1); //D到A翻转  EFABCD
	printf("%s\n",p); 
    return 0;
}


猜你喜欢

转载自blog.csdn.net/loved_computer/article/details/76430180