Is the strrev() function not available in Linux?
Correct. Use one of the alternative implementations available:
#include <string.h>
char *strrev(char *str)
{
char *p1, *p2;
if (! str || ! *str)
return str;
for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
{
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
return str;
}
#include <string.h>
char *strrev(char *str)
{
if (!str || ! *str)
return str;
int i = strlen(str) - 1, j = 0;
char ch;
while (i > j)
{
ch = str[i];
str[i] = str[j];
str[j] = ch;
i--;
j++;
}
return str;
}
Unfortunately, strrev
seems to be absent from glibc's string.h
.
Obviously, I'm late to the here's-some-code party, but I like this implementation.
#define MAX_CHARS 10000
// safe_usub -- perform safe unsigned subtraction
size_t safe_usub (size_t x, size_t y) {
return x > y ? x - y : y - x ;
}
char* str_reverse (const char* const str) {
if (!str) { return NULL; }
size_t len = strnlen(str, MAX_CHARS);
char* new = malloc( sizeof(char) * len );
size_t i;
for (i = 0; i < len; i++) {
new[i] = str[ safe_usub(i + 1, len) ];
}
new[i] = 0;
return new;
}