Exercise 1.19 - reverse a string

Question

Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time.

Solution

/**
 * Exercise 1.19 - Write a function reverse that reverses the character
 * string s; use it to write a program that reverses its input a line at a time.
 *
 **/

#include<stdio.h>

#define MAXLINE 1000

int mgetline(char line[], int lim);

void reverse(char rline[]);


int main(void)
{
  int len;
  char line[MAXLINE];

  while((len = mgetline(line, MAXLINE)) > 0 )
  {
    reverse(line);
    printf("%s",line);
  }

  return 0;
}


int mgetline(char s[],int lim)
{
  int i,c;
  
  for(i=0; i<lim-1 && (c=getchar()) != EOF && c != '\n'; ++i)
    s[i] = c;

  if( c == '\n')
  {
    s[i] = c;
    ++i;
  }
  s[i] = '\0';

  return i;
}


void reverse(char rline[])
{
  int i,j;
  char temp;

  for(i=0;rline[i]!='\0';++i)
    ;

  --i;

  if(rline[i]=='\n') --i;

  j = 0;

  while(j < i)
  {
    temp = rline[j];
    rline[j] = rline[i];
    rline[i] = temp;
    --i;
    ++j;
  }
}

Explanation

A string in C is a character array which ends in 0. getline is a function in our program, which reads one character at a time using getchar and stores it in a character array called s[] and it returns the length of the array. We call the reverse function on our line. In the reverse function, we calculate the length of the line minus 0 and n if that is present. This determines the ultimate printable characters in the line from where we have to reverse.

We have to two incides, j=0 and i the last printable character and run through the program of swapping those characters till j < i. This reverses the contents of our string.

The crux of the program is this:

    j = 0;

while(j < i)
{
  temp = rline[j];
  rline[j] = rline[i];
  rline[i] = temp;
  --i;
  ++j;
}