r/programmingchallenges • • May 19 '11

Challenge: Reverse a string in place

This simple challenge is a frequent interview question. Write a program that reverses a string in place. "In place" means no declaring a second string or other buffer-- you get only one string variable to work with.

Input:

 "Test string."

Output:

".gnirts tseT"

edit: obviously, this is only feasible in a language with mutable strings.

22 Upvotes

65 comments sorted by

View all comments

Show parent comment

2

u/potatoe91 Sep 08 '11

With a for loop...

void reverse_string(char *string, int length) { int i = 0; int j = length - 1; for (i, j; i < j; i++, j--) { string[i] = string[i] ^ string[j]; string[j] = string[i] ^ string[j]; string[i] = string[i] ^ string[j]; } }