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;
}
Tagged #ctci, #programming, #c.

Similar posts

More by Jim

Want to build a fantastic product using LLMs? I work at Granola where we're building the future IDE for knowledge work. Come and work with us! Read more or get in touch!

This page copyright James Fisher 2020. Content is not associated with my employer. Found an error? Edit this page.