编写一个函数,作用是把一个char组成的字符串循环右移n个

本文介绍了如何使用C++实现字符串的循环移位操作,包括使用`strcpy`和`memcpy`函数的不同方法来完成字符串的前缀和后缀互换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

比如原来是“abcdefghij”,如果n=2,移位后应该是“hiabcdefgh”

#include <iostream>
#include <string.h>
using namespace std;

void LoopMove(char *pStr, int steps)
{
	char *temp;
	int n = strlen(pStr) - steps;
	if(NULL==(temp = (char *)malloc((strlen(pStr)+1+steps)*sizeof(char))))
		throw "分配内存失败!";
	strcpy(temp, pStr+n);
	strcpy(temp+steps, pStr);
	*(temp + strlen(pStr)) = '\0';
	strcpy(pStr, temp);
	free(temp);
}

void LoopMove1(char *pStr, int steps)
{
	char *temp;
	int n = strlen(pStr) - steps;
	if(NULL==(temp = (char *)malloc((strlen(pStr)+1+steps)*sizeof(char))))
		throw "分配内存失败!";
	memcpy(temp, pStr+n, steps);
	memcpy(temp+steps, pStr, n);
	memcpy(pStr, temp, strlen(pStr));
	free(temp);
}


int main()
{
	int step;
	char str1[20];
	memset(str1, 0, sizeof(str1));
	scanf("%s", str1);
	scanf("%d", &step);
//	使用strcpy库函数操作
	//	LoopMove(str1, step);
//	使用memcpy库函数操作
	LoopMove1(str1, step);
	printf("%s\n", str1);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值