C语言–字符串左旋
字符串左旋:假设一个字符串ABCDEF ,左旋三个字符变为了DEFABC
这里列出来两种实现方式
- 方法一:
#include <stdio.h>
void string_left_rotate(char* arr, int size, int n)
{
for (int i = 0; i < n; i++)
{
char temp = *arr;
for (int j = 0; j < size -1; j++)
{
*(arr + j) = *(arr + j + 1);
}
*(arr + size - 1) = temp;
}
}
int main()
{
char arr[20] = "ABCDEF";
int size = strlen(arr);
int n = 3;
string_left_rotate(arr, size, n);
printf("%s\n", arr);
return 0;
}
- 方法二:
#include <stdio.h>
#include <string.h>
#include <assert.h>
void reverse(char* left, char* right)
{
assert(left);
assert(right);
while (left < right)
{
char temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
}
void string_left_rotate2(char* arr, int size, int n)
{
reverse(arr, arr + n - 1);
reverse(arr + n, arr + size - 1);
reverse(arr, arr + size - 1);
}
int main()
{
char arr[20] = "ABCDEF";
int size = strlen(arr);
int n = 3;
string_left_rotate2(arr, size, n);
printf("%s\n", arr);
return 0;
}
|