C编程实现字符串移位操作

  • 基本原理

  1. 先malloc一个n个字节大小的buff, char * buf =(char*) malloc(n);其中n为字符串求要左移的位数;

  2. 先将要求左移的字符串str的前n个字节的数据拷贝至我们刚刚创建的buf中;

  3. 利用memmove函数将str的第n个字节的数据移动至str的开始处;

  4. 在利用memcpy或strncpy将buf中的数据拷贝至str的str[strlen(str) - num]地址处。

  • 图示

C编程实现字符串移位操作_第1张图片

 C编程实现字符串移位操作_第2张图片

  • C编程实现代码

/*********************************************************************************
 *      Copyright:  (C) 2020 ysn
 *                  All rights reserved.
 *
 *       Filename:  str.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(15/08/20)
 *         Author:  tianjincheng <[email protected]>
 *      ChangeLog:  1, Release initial version on "15/08/20 12:36:35"
 *                 
 ********************************************************************************/

#include 
#include 
#include 

char *str_leftshift(char *str, int num)
{
    char * res = (char *)malloc(num);
    if (NULL == res )
        return NULL;

    if (NULL == str || num > strlen(str))
        return NULL;


    memcpy(res, str, num);
    memmove(str, &str[num], strlen(str) - num);
    memcpy(&str[strlen(str) - num], res, num);
    str[strlen(str)] = '\0';

    free(res);
    return str;
}

int main()
{
    char  dst[200];
    int  n = 0;
    memset(dst, 0, sizeof(dst));
    scanf("%s", dst);
    scanf("%d", &n);
    char * res = str_leftshift(dst, n);
    if (res != NULL)
        printf("%s\n", res);

}
  • 运行结果

C编程实现字符串移位操作_第3张图片

  •  注意

  1. ​​​​​​​千万不要放了free我们malloc产生的buf。

你可能感兴趣的:(算法)