Cracking the Coding Interview Q1.2
Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.
#include<stdio.h> #include<string.h> /** * reverse the string in place. */ void reverse(char* str) { if (str == NULL) return; int n = strlen(str); char tmp; //be careful: i<n/2, not i<=n/2; for (int i = 0; i < n / 2; i++) { tmp = str[i]; str[i] = str[n - 1 - i]; str[n - 1 - i] = tmp; } return; } int main() { char str[10] = "abcde"; reverse(str); printf("%s\n", str); }
Solution:
void reverse(char *str) { char * end = str; char tmp; if (str) { while (*end) { ++end; } --end; while (str < end) { tmp = *str; *str++ = *end; *end-- = tmp; } } }