Sure. It may not be very fast for such a size, but assuming you
can create the string in the first place it should reverse it.
Don't forget to #include <string.h>. This avoids extra calls on
strlen by returning its value.
/* ======================= */
/* reverse string in place */
size_t revstring(char *stg)
{
char *last, temp;
size_t lgh;
lgh = strlen(stg);
if (lgh > 1) {
last = stg + lgh; /* points to '\0' */
while (last-- > stg) {
temp = *stg; *stg++ = *last; *last = temp;
}
}
return lgh;
} /* revstring */
Too complicated because superflous statements.
strictly conforming, best optimised:
/* reverse a string of 0 or more bytes in length in place */
/* caller is responsible for NOT calling with a null pointer */
/* or NOT calling with a string constant */
/* return: size of the string to reverse */
size_t revstring(void *p) {
char *l = p;
/* size is needed only to get it returned!
r should be calculated: = l + strlen(l) -1; */
size_t size = strlen(p);
char *r = l + size - 1;
char c;
while (l < r) { /* when l >= r we're done */
c = *l;
*l++ = *r;
*r-- = c;
}
return size;
}
Remarks:
size < 2: nothing is done, except setup the variables.
size is uneven: the middlest char lefts untouched as it has no
counterpart
--
Tschau/Bye
Herbert
Visit
http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!