C - the string reverse

30. January 2012 08:00

A short example of doing an inplace string reverse in C

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void swap(char *a, char *b) {
    char tmp = *a;
    *a = *b;
    *b = tmp;
}


int main(int argc, char **argv) {
    if (argc < 2) {
        printf("Usage: %s <string>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    char *tmp = strdup(argv[1]);
    int len = strlen(tmp);
    int i = 0;

    for(i=0;i<len/2;i++) {
        swap(&tmp[i], &tmp[len - i - 1]);
    }

    printf("%s\n", tmp);

    free(tmp);
    return EXIT_SUCCESS;
}
E-mail Kick it! DZone it! del.icio.us Permalink


Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading