字符串 单词倒排

来源:百度知道 编辑:UC知道 时间:2024/06/01 11:05:20
程序以字符串为单位,以空格或标点为分隔符,对字符串中所有单词进行倒排,之后把已处理的字符串(不含标点)打印出来.如:原文:you he me结果:me he you
要求用c语言编写.
我是初学者,想了好长时间,都没有个结果,希望大家帮帮我.

aoqijia把C的输入输出和C++的混淆了。而且也没有处理标点。

问题不是那么简单的。下面的程序是一个实现,这里单词定义为只包括数字和字母,最长为1024个字符。
程序读到EOF,或非数字、字母、空白、标点的字符(非可打印字符,包括汉字),或一个超过1024个字符的单词后停止。
EOF在键盘上是在Dos / Windows下输入Ctrl + Z。
GCC 4编译通过。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAXWORD 1024
#define NWORD_INIT 1024

int getword(char *strarray[], int n)
{
int ch;
char word[MAXWORD + 1];
int i;
while ( isspace(ch = getchar()) || ispunct(ch) ) /* empty */;
for (i = 0; i < MAXWORD; ++i) {
if (isalnum(ch)) word[i] = ch;
else break;
ch = getchar();
}
if (i == 0) return 0;
word[i] = '\0';
strarray[n] = (char*) malloc(strlen(word) + 1);
if (strarray[n] == NULL) exit(1);
strcpy(strarray[n], word);
return 1;
}

main()