即实现一个功能,可以将一句话中的单词顺序反过来,比如:
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
下面是我自己写的一个简单的实现,不过总感觉有点别扭,可能哪里还有问题吧。
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include <ctype.h>
- void reverse_word(char *word, int len)
- {
- char tmp;
- char *end = word + len - 1;
- while (word < end) {
- tmp = *word;
- *word = *end;
- *end = tmp;
- word++;
- end--;
- }
- }
- void reverse_sentence(char *p, char *delim)
- {
- int len = strlen(p);
- reverse_word(p, len);
- int count = 0;
- while ('\0' != *p) {
- if (isspace(*p)) {
- reverse_word(p - count, count);
- count = 0; // 单词长度
- while (isspace(*++p));
- continue;
- }
- p++;
- count++;
- }
- }
- int main(int argc, char **argv)
- {
- char sentence[] = " I from nwpu, my name is cq! ";
- printf("before reverse: ^%s$\n", sentence);
- reverse_sentence(sentence, " ");
- printf(" after reverse: ^%s$\n", sentence);
- }
阅读(1015) | 评论(0) | 转发(0) |