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;
}
With Vidrio
With generic competitor
More by Jim
- Your syntax highlighter is wrong
- Granddad died today
- The Three Ts of Time, Thought and Typing: measuring cost on the web
- I hate telephones
- The sorry state of OpenSSL usability
- The dots do matter: how to scam a Gmail user
- My parents are Flat-Earthers
- How Hacker News stays interesting
- Project C-43: the lost origins of asymmetric crypto
- The hacker hype cycle
- The inception bar: a new phishing method
- Time is running out to catch COVID-19
- A probabilistic pub quiz for nerds
- Smear phishing: a new Android vulnerability
Tagged #ctci, #programming, #c. All content copyright James Fisher 2020. This post is not associated with my employer. Found an error? Edit this page.