How to reverse a string in C

Question 1.2 of Cracking the Coding Interview:

Implement a function void reverse(char* str) in C or C++ which reverses a null-terminated string.

This is (implicitly) asking for an in-place reversal of the string. We start by finding the end of the string (or equivalently, its length). Then we swap the last character and the first character, and repeat this working our way in towards the middle of the string. We stop when the string remaining to reverse is zero or one characters long (note that a one-character string reversed is itself).

Here’s a solution in C:

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

void reverse(char* s) {
  int left = 0;
  
  int len = 0;
  for (; s[len] != '\0'; len++);

  while (len > 1) {
    char left_c = s[left];
    s[left] = s[left+len-1];
    s[left+len-1] = left_c;

    left++;
    len -= 2;
  }
}

void test(char* input, char* output) {
  char* mut_input = strdup(input);
  reverse(mut_input);
  assert(strcmp(mut_input, output) == 0);
  free(mut_input);
}

int main(int argc, char** argv) {
  test("hello", "olleh");
  test("hell", "lleh");
  test("", "");
  return 0;
}
WFH on lockdown, like me? Let’s help each other out! I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. “Oh damn that's genius”, said some YouTuber when he saw it. But don't believe him, or the #1 on Product Hunt. Instead, believe this demo:

With Vidrio

With generic competitor

More by Jim

Tagged #ctci, #programming, #c. All content copyright James Fisher 2020. This post is not associated with my employer. Found an error? Edit this page.