/* revstr.c -- Copyright 1995 Liam R. Quin. All Rights Reserved. * This code is NOT in the public domain. * See the file COPYRIGHT for full details. */ /* $Id: revstr.c,v 1.2 1995/09/05 16:16:44 lee Exp $ */ #include "globals.h" #include "error.h" #include #include #include #include "lqutil.h" /* * LQU_ReverseString * Utilities/Strings * *

Reverses the bytes in the given string; if `type' is even, * the individual whitespace-delimited words are reversed in place; * if type is even, he entire string is reveresed. The process is * repeated with (type - 1) until type is zero. Hence, a reverse type * of zero does nothing, and a reverse type of one reverses the string in * place; a reverse type of 2 will reverse the order of the words in * the string; a reverse type of 3 is the same as a reverse type of one, * and a reverse type of 4 leaves the string in place. Values greater * than two are thus pointless, but are allowed for convenience. * * the given start pointer; the string is reversed in place. * *

The string must be in read-write memory; to reverse a string * that was a manifest constant at compile time, you must first copy * it into a dynamically allocated buffer. *

This function is used by lqkwic, which contains some examples. * * * An internal error (always fatal) is produced if either start or * end is a null pointer, or if end < start (implying a string of * negative length), or if the type argument is outside the range * from zero to eight inclusive. * * */ API char * LQU_ReverseString(start, end, type) char *start; char *end; int type; { /* some simple sanity checking: */ if (!start) { Error(E_FATAL|E_INTERNAL, "LQU_ReverseString: null start string"); } if (!end) { Error(E_FATAL|E_INTERNAL, "LQU_ReverseString: null end pointer"); } if (end < start) { Error(E_FATAL|E_INTERNAL, "LQU_ReverseString: end pointer < start"); } if (type < 0 || type > 8) { Error(E_FATAL|E_INTERNAL, "LQU_ReverseString: type must be between 0 and 8, not %d", type ); } for (; type > 0; --type) { /* On alternate goes we reverse the entire string or * simply individual words. * Type: Result: * 0 this is the way we were * 1 erew ew yaw eht si siht * 2 were we way the is this * 3 siht si eht yaw ew erew * 4 this is the way we were * * A Word is defined as bounded by whitespace. */ if (type & 01) { register char *p; register char *q; for (p = start, q = end; p < q; p++) { char tmp = *p; *p = *--q; *q = tmp; } } else { char *wordStart; char *wordEnd; for (wordStart = start; wordStart < end; wordStart = wordEnd) { while (wordStart < end && isascii(*wordStart) && isspace(*wordStart) ) { wordStart++; } if (wordStart >= end) { break; } for (wordEnd = &wordStart[1]; wordEnd < end; wordEnd++) { if (isascii(*wordEnd) && isspace(*wordEnd)) { break; } } LQU_ReverseString(wordStart, wordEnd, 1); } } } return start; }