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

比如原来是“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;
}



### 回答1: ``` #include<iostream> #include<string> using namespace std; void rotate_right(string& str) { char temp = str[str.length()-1]; for(int i = str.length()-1; i > 0; i--) str[i] = str[i-1]; str[0] = temp; } int main() { string str = "abcdefghijklmnopqrstuvwxyz"; for(int i = 0; i < 26; i++) { cout<<str<<endl; rotate_right(str); } return 0; } ``` ### 回答2: 以下是用C++编写循环右移字母表的程序: ```cpp #include <iostream> using namespace std; int main() { // 定义存储字母表的数组 char alphabet[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; int shift; cout << "请输入要右移的位数:"; cin >> shift; // 计算实际右移的位数 shift = shift % 26; // 右移字母表 for (int i = 0; i < 26; i++) { int newIndex = (i + shift) % 26; cout << alphabet[newIndex] << " "; } return 0; } ``` 以上程序首先定义了一个存储字母表的数组,并且接受用户输入的右移位数。然后,将输入的位数取模26,保证右移的位数在0到25之间。接下来,通过循环来计算每个字母在右移后的新位置,并输出。运行程序后,用户需要输入一个整数作为右移位数,然后程序会输出右移后的字母表。例如,如果右移位数为3,那么输出将会是"y z a b c d e f g h i j k l m n o p q r s t u v w x"。 ### 回答3: 下面是一个用C++写的循环右移字母的程序: ```cpp #include <iostream> #include <string> std::string rotateRight(std::string s, int n) { int len = s.length(); n = n % len; // 确保 n 在 0 到 len-1 之间 for (int i = 0; i < n; i++) { char lastChar = s[len - 1]; // 保存最后一个字符 for (int j = len - 1; j > 0; j--) { s[j] = s[j - 1]; // 每个字符往右移动一位 } s[0] = lastChar; // 最后一个字符移到开头 } return s; } int main() { std::string alphabet = "abcdefghijklmnopqrstuvwxyz"; int shift = 3; std::string rotatedAlphabet = rotateRight(alphabet, shift); std::cout << "旋转后的字母表: " << rotatedAlphabet << std::endl; return 0; } ``` 这个程序使用了一个 `rotateRight` 函数,它接受一个字符串和右移的位数,返回右移后的字符串。在 `main` 函数中,我们声明了一个字母表字符串 `alphabet` 和一个要右移的位数 `shift`(在这个例子中是3)。然后我们调用 `rotateRight` 函数来计算右移后的字母表,并打印结果。最后输出的结果是 `旋转后的字母表: defghijklmnopqrstuvwxyzabc`,即将字母表右移了3位。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值