题目:将字符串str循环左移n次,例如字符串str = “hello”, 左移三次得到"lohel"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void leftRotateString(char* str, int n) {
int len = strlen(str);
if (len == 0 || n == 0) return;
n = n % len;
char* temp = (char*)malloc(n + 1);
if (temp == NULL) {
return;
}
memcpy(temp, str + len - n, n);
temp[n] = '\0';
memmove(str, str + n, len - n);
memcpy(str, temp, n);
free(temp);
}
int main() {
char str[100];
int n;
printf("请输入待左移的字符串: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = 0;
printf("请输入左移位数: ");
scanf("%d", &n);
leftRotateString(str, n);
printf("左移后的字符串为: %s\n", str);
return 0;
}