Learn more about Russian war crimes in Ukraine.

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;
}

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

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.