09-11-13:C语言字符串的循环右移

//实现的功能
//input:   abcdefg                                                                                                                                    
//         2
//output: fgabcd
//input:   abcdefg
//        -2
//output: cdefgab

#include <stdio.h>

int main() {
    char a[100], b[100];
    int n;
    /*
    * 输入字符串,保存到a中
    */

    printf("Please input your string: ");
    scanf("%s", a);
    printf("/n");
    /*
    * 输入移位次数,保存到n中
    */

    scanf("%d", &n);

    /*
    * 获得字符串的长度
    */

    int string_length;
    for (string_length = 0; a[string_length] != '/0'; ++string_length)
        ;
    /*
    * 移位
    */

    int i, j;
    if (n > 0) {
        for (i = string_length + n; i >= n; i--)
            a[i] = a[i-n];
        for (i = 0; i < n; i++)
            a[i] = a[string_length+i];
    }
    else if (n < 0) {
        for (i = string_length; i <=string_length-n; i++)
            a[i] = a[i-string_length];
        for (i = 0; i <= string_length; i++)
            a[i] = a[i-n];
    }
    else
        ;

    a[string_length] = '/0';
    printf("/n%s/n", a);
    return 0;  
}

 

 

 

 

 #include <stdio.h>   

#include <stdlib.h>   

  1. void loopMove(char *pStr,int steps)   
  2. {   
  3.     int length=0,i=0;   
  4.     char *sub=pStr,*str;   
  5.   
  6.     while (*pStr!='/0')   
  7.     {   
  8.         length++;   
  9.         pStr++;   
  10.     }   
  11.     pStr--;   
  12.     if (steps>length)   
  13.         steps=steps-length;   
  14.     str=(char *)malloc(steps);   
  15.   
  16.     for (i=0;i<steps;i++)   
  17.         str[i]=sub[length-steps+i];   
  18.        
  19.     for (i=0;i<length-steps;i++)   
  20.         sub[length-i-1]=sub[length-steps-i-1];   
  21.   
  22.     for (i=0;i<steps;i++)   
  23.         sub[i]=str[i];   
  24.   
  25. }   
  26.   
  27. int main()   
  28. {   
  29.     char a[]="abcdef";   
  30.     loopMove(a,7);   
  31.     printf("%s/n",a);   
  32.   
  33.     return 0;   
  34. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值