C语言,实现字符串的移动
时间: 2023-05-19 08:01:27 浏览: 146
可以使用循环移位的方法来实现字符串的移动。具体实现方法如下:
```c
#include <stdio.h>
#include <string.h>
void leftRotateString(char* str, int n)
{
int len = strlen(str);
if (len == 0 || n % len == 0) {
return;
}
n %= len;
char temp;
for (int i = 0, j = n - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
for (int i = n, j = len - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
for (int i = 0, j = len - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
int main()
{
char str[] = "abcdefg";
int n = 3;
leftRotateString(str, n);
printf("%s\n", str);
return 0;
}
```
这段代码可以将字符串 "abcdefg" 向左移动 3 个位置,输出结果为 "defgabc"。