C language pointer-reverse and left rotation of string

1. Write a function that can reverse the contents of a string:

For example, enter HelloWorld and output dlroWolleH

#include<stdio.h>
#include<string.h>                //字符串函数的头文件
void NiZhi(char arr[])
{
	char temp = 0;                            //设置一个空变量为以下交换做准备
	char* left = arr;                         //记入首元素的地址
	char* right = arr + strlen(arr) - 1;      //记入末元素的地址
	while (left < right)                  //防止越界访问,循环条件设为left<right
	{
		temp = *left;
		*left = *right;                   //完成首尾元素位置交换
		*right = temp;
		left++;                       //每进行一次循环,left就往前进一步,right就往后退一步
		right--;
	}
}
int main()
{
	char arr[100] = { 0 };
	while (gets(arr))                 //这里用gets输入整个字符串,切记由空隔不能用scanf
	{                                 //scanf只会记入到空隔前一个字符
		NiZhi(arr);
		printf("%s\n", arr);
	}
	return 0;
}

 

2. Implement a function that can left-rotate k characters in a string

For example, if you rotate ABCD one character to the left, you get BCDA, and if you rotate ABCD two characters to the left, you get CDAB.

#include<stdio.h>
#include<string.h>
void ZuoXuan(char arr[],int time)             //将首元素的地址和进行的趟数传给函数
{
	int len = strlen(arr);                   
 	time %= len;                             
	//计算具体的趟数,例如左旋1次是BCDA,左旋5次也是BCDA,4个为一个循环;
 	for (int i = 0; i < time; i++)
	{
		char temp = arr[0];                //要挪动的元素   
		int j = 0;
		for (j = 0; j < len - 1; j++)      //开始挪动        如果j = len,arr[j+1]下标越界访问不行
		{
			arr[j] = arr[j + 1];           //本质就是后一个数覆盖前一个数在将挪动元素放在后面
		}
		arr[j] = temp;                     //放回元素
	}
}
int main()
{
	char arr[] = "ABCD";
	ZuoXuan(arr, 2);
	printf("%s\n", arr);
	return 0;
}

 We can also use the three-dimensional rotation method

A B C D E F(左旋两个数)
0 1 2 3 4 5
AB    CDEF
01    2345
BA    FEDC(AB旋转一次,CDEF旋转一次)
01    2345
CDEFAB(整体旋转一次)
#include<stdio.h>
#include<string.h>
void NiZhi1(char arr[], int start, int end)
{                      
	int left = start;
	int right = end;
	while (left < right)
	{
		char temp = arr[left];        
		arr[left] = arr[right];
		arr[right] = temp;
		left++;
		right--;
	}
}
void NiZhi2(char arr[], int time)
{
	int len = strlen(arr);
	time %= len;
	NiZhi1(arr, 0, time - 1);      //左半旋转的区间,例如左旋两个数,time就是2,time-1 = 1
                                   //就是下标0到1的数AB
	NiZhi1(arr, time, len - 1);    //右半旋转的区间
	NiZhi1(arr, 0, len - 1);       //整体旋转
}
int main()
{
	char arr[] = "ABCDEFG";
	NiZhi2(arr, 2);
	printf("%s\n", arr);
	return 0;
}

Guess you like

Origin blog.csdn.net/2301_79201049/article/details/134532067