I thought of this algorithm today. It seems fast, but how can I know?
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
/*
* Reverse a string
* the caller has to free dynamic memory allocated
*/
char *mon_string_rev(char *string)
{
char *out = malloc ( strlen(string) + 1 );
assert(out);
int len = strlen(string);
int i;
int counter = 0;
int iterations = 0;
while(1) {
if(len < 0) break;
// important to only start counting after
// determing that the loop will continue
++iterations;
for(i = 0; i < len; i++) {
// if this is the last character
// push it onto the output string
if(i == (len - 1)) {
out[counter] = string[i];
counter++;
}
}
len--;
}
out[counter] = '\0';
printf("Total iterations: %d\n", iterations);
return out;
}
int main(int argc, char **argv)
{
if(argc < 2) {
fprintf(stderr, "Usage: %s <string>", argv[0]);
exit(1);
}
char *str = mon_string_rev(argv[1]);
printf("%s\n", str);
free(str);
return !1;
}
Edit Thank you everyone for the suggestions, and feedback. My weakness is taking criticism, but I am working on it.
I woke up one day and wanted to write a string reverse function. This was my first attempt at implementing it completely on my own without referencing past implementations. So, I thought I was clever with the infinite loop and breaking condition.
This is my updated version based all the suggestions. The caller passes the length and manages memory: https://github.com/rmccullagh/snippets/tree/master/c/string2