Exercise: String reversing, Kurt Nørmark

Solution index                   Textual C program


/* Programmed by Kurt Nørmark, April 2003 */

#include <stdio.h>

void swap(char *p, char *q){
   char   tmp;

   tmp = *p;
   *p = *q;
   *q = tmp;
}

void string_reverse(char *s){
  char *s_front, *s_rear;

  for (s_front = s, s_rear =  s + strlen(s) - 1;
       s_front < s_rear;
       s_front++, s_rear--)
    swap(s_front, s_rear);
}

int main(void) {

  char str[] = "computer"; 

  printf("%s\n", str);
  string_reverse(str);
  printf("%s\n", str);
  
  return 0;
}

We write a function which reverses the characters in a string. Our function is iterative, because it uses a loop. We could also write a recursive solution. As an imporant property, the function mutates the characters in the existing string. Alternatively, we could have made a solution that returns a new, fresh string.
 

void swap(char *p, char *q){
   char   tmp;

   tmp = *p;
   *p = *q;
   *q = tmp;
}
We need the swap function, which we have seen before. Notice the call by reference parameters of type char *.
 

void string_reverse(char *s){
  char *s_front, *s_rear;

  for (s_front = s, s_rear =  s + strlen(s) - 1;
       s_front < s_rear;
       s_front++, s_rear--)
    swap(s_front, s_rear);
}
The string_reverse function takes a single string parameter. In a for loop we first swap the first and the last char. The terminating '0' char is not affected. The two local pointer variables s_front and s_rear are then incremented and decremented respectively. Eventually, they meat or cross in which case we are done. Notice that in case there are an odd number of characters, the middle one needs not to be moved.
 

int main(void) {

  char str[] = "computer"; 

  printf("%s\n", str);
  string_reverse(str);
  printf("%s\n", str);
  
  return 0;
}
We try out the function on a fixed string "computer". Notice one thing here. If we had declared str as char *str = "computer" instead we were not allowed to modify it in swap. We get a segmentation fault. In general, we need to declare strings in the array fashion shown above, if we need to modify the string.
 


Generated: Wednesday, March 29, 2006, 12:33:07
This program dissection page is generated from an XML-in-LAML source file