Chinaunix首页 | 论坛 | 博客
  • 博客访问: 21214
  • 博文数量: 9
  • 博客积分: 25
  • 博客等级: 民兵
  • 技术积分: 57
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-27 10:58
文章分类

全部博文(9)

文章存档

2014年(6)

2013年(3)

我的朋友

分类: C/C++

2014-04-03 00:51:25

输入一个英文句子,对句子中的单词逆序。其中"-"作为单词连接符,"--"作为单词分隔符
比如,I am a student, 逆序之后为student a am I。

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. int reverse(char* strOut, const char* strIn)
  4. {
  5.     if (NULL == strOut || NULL == strIn)
  6.     {
  7.         return -1;
  8.     }

  9.     const char* pTraIn = strIn;
  10.     char strTmp[40] = {'\0'};
  11.     char* pTmp = strTmp;

  12.     while (*pTraIn != '\0')
  13.     {
  14.         pTraIn++;
  15.     }
  16.     pTraIn--;

  17.     while (pTraIn != strIn - 1)
  18.     {
  19.         if ((*pTraIn >= 'a' && *pTraIn <= 'z') ||
  20.             (*pTraIn >= 'A' && *pTraIn <= 'Z') ||
  21.             (*pTraIn == '-' && ((*(pTraIn+1) >= 'a' && *(pTraIn+1) <= 'z') ||
  22.                                 (*(pTraIn+1) >= 'A' && *(pTraIn+1) <= 'Z')
  23.                              )
  24.                              && ((*(pTraIn-1) >= 'a' && *(pTraIn-1) <= 'z') ||
  25.                                 (*(pTraIn-1) >= 'A' && *(pTraIn-1) <= 'Z')
  26.                              )
  27.             ) ||
  28.             ('\'' == *pTraIn)
  29.          )
  30.         {
  31.             *pTmp++ = *pTraIn--;
  32.         }
  33.         else
  34.         {
  35.             if (pTmp != strTmp)
  36.             {
  37.                 pTmp--;
  38.                 while (pTmp != strTmp)
  39.                 {
  40.                     *strOut++ = *pTmp--;
  41.                 }
  42.                 *strOut++ = *pTmp;
  43.                 *strOut++ = ' ';
  44.             }
  45.             pTraIn--;
  46.         }
  47.     }
  48.     if (pTmp != strTmp)
  49.     {
  50.         pTmp--;
  51.         while (pTmp != strTmp)
  52.         {
  53.             *strOut++ = *pTmp--;
  54.         }
  55.         *strOut++ = *pTmp;
  56.     }
  57.     *strOut = '\0';
  58.     
  59.     return 0;
  60. }

  61. int main()
  62. {
  63.     char str1[] = "I am a student";
  64.     char str2[] = "he-llo, may--be I'm . a student";
  65.     char str3[] = ". hello, i am a student.. *";
  66.     char strRet[200];

  67.     reverse(strRet, str1);
  68.     puts(strRet);
  69.     reverse(strRet, str2);
  70.     puts(strRet);
  71.     reverse(strRet, str3);
  72.     puts(strRet);

  73.     return 0;
  74. }


阅读(519) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~