函数实现字符串循环右移 n 位。(思考不同方法的效率问题)比如: “abcdefgh”循环右移 3 位后,结 果为:”fghabcde” C语言使用三种方法实现
时间: 2023-05-24 07:01:11 浏览: 110
方法一:
```c
#include <stdio.h>
#include <string.h>
void rightRotateString(char *str, int n) {
int len = strlen(str);
if (len == 0 || n == 0) {
return;
}
n %= len;
char temp;
for (int i = 0; i < n; i++) {
temp = str[len - 1];
for (int j = len - 1; j > 0; j--) {
str[j] = str[j - 1];
}
str[0] = temp;
}
}
int main() {
char str[] = "abcdefgh";
rightRotateString(str, 3);
printf("%s\n", str);
return 0;
}
```
方法二:
```c
#include <stdio.h>
#include <string.h>
void rightRotateString(char *str, int n) {
int len = strlen(str);
if (len == 0 || n == 0) {
return;
}
n %= len;
char temp[n];
strncpy(temp, str + len - n, n);
memmove(str + n, str, len - n);
memcpy(str, temp, n);
}
int main() {
char str[] = "abcdefgh";
rightRotateString(str, 3);
printf("%s\n", str);
return 0;
}
```
方法三:
```c
#include <stdio.h>
#include <string.h>
void swap(char *a, char *b) {
char temp = *a;
*a = *b;
*b = temp;
}
void reverse(char *begin, char *end) {
while (begin < end) {
swap(begin++, end--);
}
}
void rightRotateString(char *str, int n) {
int len = strlen(str);
if (len == 0 || n == 0) {
return;
}
n %= len;
reverse(str, str + len - 1);
reverse(str, str + n - 1);
reverse(str + n, str + len - 1);
}
int main() {
char str[] = "abcdefgh";
rightRotateString(str, 3);
printf("%s\n", str);
return 0;
}
```
阅读全文