C语言实现文本语句以单词为单位逆序
Reverse text by words in C language:
e.g.
source = "We are meeting now,too."
dest = ".too,now meeting are We"
Main 函数的参数为待逆序的文本串。
--------------------------------------------File reverser.c begin-------------------------------------------
/***************************************************************************
* Copyright (C) 2009 by SG-BJ-DC *
* sg@sg-laptop.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <ctype.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_LENGTH 100
char* ReversedText(char *originalText);
int main(int argc, char *argv[])
{
int i = 0;
char *reversedSentence = NULL;
while (++i < argc)
{
printf("Index %d of original argument: /"%s/"/n",i,argv[i]);
reversedSentence = ReversedText(argv[i]);
printf("Index %d of reversed argument: /"%s/"/n",i,argv[i]);
printf("Return the %dth Reversed Text: /"%s/"/n",i,reversedSentence);
}
return EXIT_SUCCESS;
}
char* ReversedText(char *originalText)
{
int textLength = 0;
int wordCount = 0;
int wordlength = 0;
char reversingText[MAX_LENGTH];
int i = 0;
int j = 0;
assert(originalText != NULL);
textLength = strlen(originalText);
reversingText[textLength] = '/0';
printf("Original Text:/"%s/"/n", originalText);
while (i < textLength)
{
for (j = i; (j < textLength) && (isalnum(originalText[j]) || ('-' == originalText[j])); j++)
{
//blank block
}
wordlength = j-i;
if (wordlength > 0)
{
memcpy(reversingText + textLength - j, originalText + i,wordlength);
wordCount++;
wordlength = 0;
}
else
{
//Blank block
}
if (j < textLength)
{
reversingText[textLength - j - 1] = originalText[j];
}
else
{
break;
}
i = j+1;
}
reversingText[textLength] = '/0';
memcpy(originalText, reversingText, textLength);
printf("Reversed Text:/"%s/"/n",originalText);
printf("Total %d words reserved./nTotal %d characters in length./n",wordCount,textLength);
return originalText;
}
--------------------------------------------File reverser.c end-------------------------------------------