Chinaunix首页 | 论坛 | 博客
  • 博客访问: 477366
  • 博文数量: 47
  • 博客积分: 2044
  • 博客等级: 上尉
  • 技术积分: 400
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-11 15:50
文章分类

全部博文(47)

文章存档

2012年(1)

2011年(19)

2010年(27)

我的朋友

分类: C/C++

2010-11-17 14:33:23

编写一个函数,作用是把一个char组成的字符串循环右移n个。比如原来是“abcdefghi”如果n=2,移位后应该是“hiabcdefgh” 
view plaincopy to clipboardprint?
bool moveToRightNSteps(char * start, unsigned int n)  
{  
    if( (start == NULL)) return false;  
      
    unsigned int length = strlen(start);  
    if(length != 0)  
    {  
        // while n > string length, n%length to avoid repeat operation  
        n = n%length;  
          
        int m = length - n;         // the starting m num should be moved to the end  
        char * tmp = new char[length + n + 1];      // temporary char array to help move string  
        if(tmp == NULL) return false;  
        //strcpy(tmp, start + m);  
        memcpy(tmp, start + m, n * sizeof(char));  
          
        //strcpy(tmp + n, start);  
        memcpy(tmp + n, start, m* sizeof(char));  
        //tmp[length] = '\0';  
        *(tmp + length) = '\0';  
        memcpy(start, tmp, length*sizeof(char));  
 
        delete [] tmp;  
        tmp = NULL;  
    }  
 
    return true;      
阅读(2801) | 评论(0) | 转发(0) |
0

上一篇:文本流和二进制流

下一篇:用Gcc制作Library

给主人留下些什么吧!~~