Skip to content

Instantly share code, notes, and snippets.

@bamacken
Last active April 9, 2019 23:21
C-Code demonstrates in-place strings reverse.
#include "pch.h"
#include <iostream>
// Implement "reverse" to reverse the passed string in-place.
void reverse(char *string)
{
int length = strlen(string); // cache string length
int j = 0; // first to last increment
// loop over string elements, last to first
for (int i = length - 1; i >= 0; i--)
{
char last = string[i]; // store last char
char first = string[j]; // store first char
string[i] = first; // add first to last
string[j] = last; // add last to first
// check if we have reached the mid point, if so break
if (i == j)
{
break;
}
else
{
j++;
}
}
}
int main() {
char astring[] = "Hello, tacocat.";
reverse(astring);
printf("%s\n", astring);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment