Chinaunix首页 | 论坛 | 博客
  • 博客访问: 35210
  • 博文数量: 10
  • 博客积分: 246
  • 博客等级: 二等列兵
  • 技术积分: 155
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-02 10:56
文章分类
文章存档

2012年(10)

我的朋友

分类: C/C++

2012-11-05 19:12:50


即实现一个功能,可以将一句话中的单词顺序反过来,比如:
America and China are both great countries.
反过来显示就应该是:
countries. great both are China and America
单词的分隔符以空格符为准。

思路很简单,分两步:
1、将整句话看作一个单词,进行逆序:
.seirtnuoc taerg htob era anihC dna aciremA
2、以空格为分隔符,将每个单词再进行逆序:
countries. great both are China and aciremA

下面是我自己写的一个简单的实现,不过总感觉有点别扭,可能哪里还有问题吧。

点击(此处)折叠或打开

  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. #include <ctype.h>

  5. void reverse_word(char *word, int len)
  6. {
  7.     char tmp;
  8.     char *end = word + len - 1;
  9.     while (word < end) {
  10.         tmp = *word;
  11.         *word = *end;
  12.         *end = tmp;
  13.         word++;
  14.         end--;
  15.     }
  16. }

  17. void reverse_sentence(char *p, char *delim)
  18. {
  19.     int len = strlen(p);
  20.     reverse_word(p, len);

  21.     int count = 0;
  22.     while ('\0' != *p) {
  23.         if (isspace(*p)) {
  24.             reverse_word(p - count, count);
  25.             count = 0; // 单词长度
  26.             while (isspace(*++p));
  27.             continue;
  28.         }
  29.         p++;
  30.         count++;
  31.     }
  32. }

  33. int main(int argc, char **argv)
  34. {
  35.     char sentence[] = " I from nwpu, my name is cq! ";
  36.     printf("before reverse: ^%s$\n", sentence);
  37.     reverse_sentence(sentence, " ");
  38.     printf(" after reverse: ^%s$\n", sentence);
  39. }

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