C++:循环平移的实现
在很多场景中,需要将一个数组或字符串按照指定的位数进行循环平移,具体实现方法有很多种。下面是一种基于C++语言的实现方式:
#include <iostream>
#include <cstring>
void rotate(char* str, int shift) {
int len = strlen(str);
shift %= len;
if (shift == 0) {
return;
}
char tmp[shift];
memcpy(tmp, str + len - shift, shift * sizeof(char));
memmove(str + shift, str, (len - shift) * sizeof(char));
memcpy(str, tmp, shift * sizeof(char));
}
int main() {
char s[] = "abcdefg";
rotate(s, 3);
std::cout << s << std::endl;
return 0;
}
上面的代码中,函数rotate
接收两个参数,第一个参数是需要进行平移的字符数组,第二个参数是需要平移