Chinaunix首页 | 论坛 | 博客
  • 博客访问: 138081
  • 博文数量: 30
  • 博客积分: 887
  • 博客等级: 准尉
  • 技术积分: 342
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-03 19:11
文章分类

全部博文(30)

文章存档

2012年(19)

2011年(1)

2010年(6)

2009年(4)

我的朋友

分类: C/C++

2012-02-03 21:51:20


  1. 编写一个函数,作用是把一个 char 组成的字符串循环右移 n 个。比如原来是“abcdefghi”
  2. 如果 n=2,移位后应该是“hiabcdefgh”  
  3. 函数头是这样的:  
  4. //pStr 是指向以'\0'结尾的字符串的指针  
  5. //steps 是要求移动的 n  
  6. void LoopMove ( char * pStr, int steps )  
  7. {  
  8. //请填充...  
  9. }
  10. 方法一:
  11. void  LoopMove (char *pStr, int len)
  12. {
  13.     char *newstr = NULL;
  14.     int strlenght = strlen(pStr);
  15.     int i;

  16.     newstr = (char *)malloc(len + 1);
  17.     if (newstr == NULL)
  18.     {
  19.         printf("Malloc Error\n");
  20.     }
  21.     memset(newstr,0, len+1);

  22.     for (i=0; i<len; i++)
  23.     {
  24.         *newstr++ = *(pStr + strlenght - len + i);
  25.     }

  26.     for (i=strlenght-len; i>0; i--)
  27.     {
  28.         *(pStr+len+i-1) = *(pStr + i - 1);
  29.     }

  30.     for (i=0; i<len; i++)
  31.     {
  32.         *(pStr + len - i -1) = *(--newstr);
  33.     }
  34. }
方法二:
  1. void LoopMove ( char *pStr, int steps )
  2. {
  3.     int n = strlen( pStr ) - steps;
  4.     char tmp[MAX_LEN];
  5.     strcpy ( tmp, pStr + n );
  6.     strcpy ( tmp + steps, pStr);
  7.     *( tmp + strlen ( pStr ) ) = '\0';
  8.     strcpy( pStr, tmp );
  9. }
方法三:
  1. void LoopMove ( char *pStr, int steps )
  2. {
  3.     int n = strlen( pStr ) - steps;
  4.     char tmp[MAX_LEN];
  5.     memcpy( tmp, pStr + n, steps );
  6.     memcpy(pStr + steps, pStr, n );
  7.     memcpy(pStr, tmp, steps );
  8. }
阅读(5874) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

Bruce_Lee_04182015-08-16 11:07:11

您好,我试了一下程序,但是运行不了是什么原因?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 200
void LoopMove(char *pStr,int step);
void LoopMove1(char *pStr,int step);
int main(){
 char *c = \"1234567890\";
 printf(c);
 LoopMove1(c,1);
 printf(c);
 return 1;

void LoopMove(char *pStr,int step){
 int n = strlen(pStr)-step;
 char temp[MAX_SIZE]