← All problems · Pointers & Strings
Reverse a Writable String In Place
Reverse a valid NUL-terminated writable string without allocating memory.
Implement void reverse(char *s).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Swap opposite characters.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
void reverse(char *s)
{
size_t n=0; while(s[n])++n; for(size_t i=0;i<n/2;++i){char t=s[i];s[i]=s[n-1-i];s[n-1-i]=t;}
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
void reverse(char *s)
{
std::size_t n=0; while(s[n])++n; for(std::size_t i=0;i<n/2;++i){char t=s[i];s[i]=s[n-1-i];s[n-1-i]=t;}
}
Two indices reverse the bytes in linear time and constant space.
solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
char a[]="abc", b[]="";
CHECK((reverse(a),strcmp(a,"cba")==0));
CHECK((reverse(b),strcmp(b,"")==0));
CHECK((reverse(a),strcmp(a,"abc")==0));
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}