/*
* reverse sentence word by word.
* $Id$
*/
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#if !defined(isblank)
static __inline__ int isblank(char c)
{
if (c == ' ' || c == '\t')
return (1);
else
return (0);
}
#endif
/*
* Implement a function to reverse a sentence word by word in C language,
* for example, reverse the sentence "we are good student"
* to "student good are we"
*
* input: 'str', the string to be reversed, must be mutable, since
reversed string will be stored in.
* return: a pointer to the reversed string.
* NOTE: 1. 'str' must be mutable, say, it must be a char array;
* 2. punctuation will be treated as non-blank characters.
*/
char * reverseSentenceByWords(char * str)
{
int len;
char * tStr;
char * p;
char * q;
/*
* validate and handle special cases
*/
if (!str)
return (NULL);
if ((len = strlen(str)) == 0)
return (str);
tStr = (char *)malloc((len + 1) * sizeof(char));
if (!tStr)
return (NULL);
/*
* parse and reverse, word by word, from end to beginning
*/
memset(tStr, 0, len + 1);
p = str + len - 1;
q = tStr;
while (1) {
/*
* split out blank substring and duplicate the
* substring to proper position of tStr
*/
if ((p >= str) && isblank(*p)) {
for (;(p > str) && isblank(*p); p--)
;
if (p == str) {
strcpy(q, p);
q += strlen(p);
break;
} else {
strcpy(q, p+1);
q += strlen(p+1);
*(p+1) = '\0';
}
}
/*
* split out non-blank substring and duplicate
* it to proper position of tStr
*/
if ((p >= str) && (! isblank(*p))) {
for (;(p > str) && (! isblank(*p)); p--)
;
if (p == str) {
strcpy(q, p);
q += strlen(p);
break;
} else {
strcpy(q, p+1);
q += strlen(p+1);
*(p+1) = '\0';
}
}
}
/*
* terminating tStr, copy back to str, and free tStr
*/
*(q+1) = '\0';
strcpy(str, tStr);
free(tStr);
return (str);
}
|