Here's another question that is often asked, reversing a string in C. I think most people can get through this one easily, creating a temporary char variable and swapping the first and last values. However, I came across a slight optimization to this method:
char *strrev2(char *s,int n) { int i=0; while (i<n/2) { //uses the null character as the temporary storage, // for the front character. *(s+n) = *(s+i); // swap the front and last character. *(s+i) = *(s + (n - i -1)); // put the front character in n-1 position. *(s+n-i-1) = *(s+n); i++; } // tie off the string with the NULL character. *(s+n) = '\0'; return s; } char* strrev(char* s) { return strrev2(s, strlen(s)); }
With this example, you don't need a temporary variable. You use the char at the end of the string, the one that holds the NULL (\0) character that marks the end of the string. Just remember to put the NULL character back when you are done.
A slight twist: afterward, the interviewer may ask you how to reuse this code to reverse a sentence. This is why I wrote strrev2. I won't write the code that does this, but here's the general algorithm:
- Call strrev to reverse the entire string at one time.
- Take the new string, parse the tokens separated by whitespace and delimeters.
- Reverse each token inside the reversed sentence string.
- The result should be a perfectly reversed string.

Leave a comment