#include
#include
#include
#include
//Constants
#define LINELENGTH 100
// Function prototypes
void reverse_words(char* words[], char* rwords[], int count);
void print_words(char* words[]);
int mark_words(char* line, char* words[]);
// Main Function
int main( void )
{
char *line;
char *words[51];
char *rwords[51];
int count;
if(( line = (char*) malloc(LINELENGTH * sizeof(char))) == NULL ) {
return 1;
}
strcpy(line, "this is a sample line to be broken into words.");
count = mark_words( line, words );
reverse_words( words, rwords, count );
print_words( rwords );
return 0;
}
/*
Converts line to a packed string of words and puts
pointers to each word in words[].
returns the number of words it found.
/
int mark_words( char line, char* words[] )
{
int i, count = 1;
char inbetween = 0;
words[0] = line;
for( i=0; line[i] != 0 ; ++i ) {
if( isspace( line[i] )) {
inbetween = 1;
line[i] = '\0';
}
else { // i.e. line[i] is not a whitespace character
if( inbetween ) {
inbetween = 0;
words[count++] = line + i;
}
}
}
words[count] = NULL;
return count;
}
/*
Copies the pointers in words[] to rwords[] in reverse order.
count is the number of pointers in words[]
/
void reverse_words( char words[], char* rwords[], int count )
{
int j = 0;
for( j = 0; words[j] != '\0'; j++ ) {
rwords[j] = words[count-j-1];
}
rwords[j] = '\0';
}
/*
Prints each word in words[] to stdout in order and preceded by its number.
/
void print_words( char words[] )
{
int k;
for( k=0; words[k] != 1; k++ ) {
printf("%2d. %s\n", k+1, words[k]);
}
}
int mark_words(char* line, char* words[]);
主要的用途是,把一行的單詞按空格分開,每個單詞的字符串指針放到words數組裡面,並返回單詞個數
void print_words(char* words[]);
打印words數組中每一個單詞
void reverse_words(char* words[], char* rwords[], int count);
把words數組中的單詞按逆序反過來,放到rwords數組中
測試是
this is a sample line to be broken into words.
輸出結果是