三种方法实现一个函数,可以左旋字符串中的k个字符

来源:互联网 发布:属性数据分析 编辑:程序博客网 时间:2024/05/15 01:43

实现一个函数,可以左旋字符串中的k个字符。

如:ABCD左旋一个字符得到BCDA
  ABCD左旋两个字符得到CDAB

方法一:普通方式:将需要左旋的字符存起来,再将其余部分整体左移
方法二:将字符串一分为二,先局部逆置,再整体逆置
方法三:复制字符串,将其连接起来,如:abcdefgabcdefg,若左旋3次,就从d开始截取直到c

方法一代码如下:
#include <stdio.h>#include <windows.h>#include <assert.h>#include <string.h>static void LeftOnce(char str[], int lenght){    int tmp = str[0];    int i = 0;    for (i = 0; i<lenght - 1; i++)    {        str[i] = str[i + 1];    }    str[i] = tmp;}void LeftRotate(char str[], int lenght, int num){    assert(str);    assert(lenght > 0);    assert(num > 0);    num %= lenght;      //有效次数    while (num)    {        LeftOnce(str, lenght);        num--;    }}int main(){    int num = 0;    printf("please input a number:");    scanf("%d", &num);    char str[] = "abcdefg";    printf("before:%s\n", str);    LeftRotate(str, strlen(str), num);    printf("after:%s\n", str);    return 0;}

#####方法二代码如下:

#include <stdio.h>#include <windows.h>#include <assert.h>#include <string.h>static reverse(char *p, char *q){    while (p<q)    {        *p ^= *q;        *q ^= *p;        *p ^= *q;        p++, q--;    }}void LeftRotate(char str[], int lenght, int num){    assert(str);    assert(lenght > 0);    assert(num > 0);    num %= lenght;      //有效次数    reverse(str, str + num - 1);        //局部逆置    reverse(str + num, str + lenght - 1);    reverse(str, str + lenght - 1);        //整体逆置}int main(){    int num = 0;    printf("please input a number:");    scanf("%d", &num);    char str[] = "abcdefg";    printf("before:%s\n", str);    LeftRotate(str, strlen(str), num);    printf("after:%s\n", str);    return 0;}

#####方法三代码如下:

#include <stdio.h>#include <windows.h>#include <assert.h>#include <string.h>#include <stdlib.h>void LeftRotate(char str[], int lenght, int num){    assert(str);    assert(lenght > 0);    assert(num > 0);    num %= lenght;      //有效次数    int size = 2 * lenght + 1;    char *p = (char*)malloc(sizeof(char)*size);    strcpy(p, str);    strcat(p, str);     //将两字符串拼接    strncpy(str, p + num, lenght);    free(p);}int main(){    int num = 0;    printf("please input a number:");    scanf("%d", &num);    char str[] = "abcdefg";    printf("before:%s\n", str);    LeftRotate(str, strlen(str), num);    printf("after:%s\n", str);    return 0;}
阅读全文
0 0
原创粉丝点击