随笔 - 13, 文章 - 18, 评论 - 18, 引用 - 0
数据加载中……

颠倒单词顺序

如 将字符串 "Do or do not, there is no try."
   转换为 "try. no is there not,do or Do"
 
int ReverseWords(char str[])
{
  char *buffer;
  int tokenReadPos, wordReadPos, wordEnd, writePos = 0;
 
  tokenReadPos = strlen(str)-1;
  
  buffer = (char*)malloc(tokenReadPos+2);
  if(!buffer)
    return;
 
  while(tokenReadPos>=0)
  {
     if(str[tokenReadPos] == '')
      {
          buffer[writePos++] = str[tokenReadPos--];
      }
      else
      {
          wordEnd = tokenReadPos;
          while(tokenReadPos>=0 && str[tokenReadPos]!='')
          {
             tokenReadPos--;
          }
          wordReadPos = tokenReadPos+1;
         while(wordReadPos<=wordEnd)
         {
            buffer[writePos++] = str[wordReadPos++];
         }
      }
  }
  buffer[writePos]='\0';
  strcpy(str, buffer);
 
  free(buffer);
  return 1;
}

posted on 2007-02-03 10:15 JackLi 阅读(385) 评论(0)  编辑 收藏 引用 所属分类: Examination


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理