L-13 MCS 275 Wed 7 Feb 2001

Below are the listings for the programs we discussed in class.

See Lecture 11 for the recursive function that returns the string with all characters reversed.

/* L-13 MCS 275 string handling using recursion */

#include <stdio.h>

#define MAXLEN 80

int r_strlen (const char *s);
/* returns number of characters in s before '\0' */
int strequ (const char *s1, const char *s2);
/* returns 1 if both strings are the same, 0 otherwise */
int r_strcmp (const char *s1, const char *s2);
/* returns 0 if both strings are equation, 
   a negative number if *s1 lexicographically less than *s2, and
   a positive number if *s1 lexicographically larger than *s2 */

int main()
{
   char word1[MAXLEN],word2[MAXLEN];
   const char *testw = "constant";

   printf("Give a word : ");
   scanf("%s", word1);
   printf("Number of characters in the word : %d\n", r_strlen(word1));
   printf("Number of characters in \"constant\" : %d\n", r_strlen(testw));
   printf("Give another word : ");
   scanf("%s", word2);
   printf("  \"%s\" and \"%s\"", word1,word2);
   if (strequ(word1,word2) == 1)
      printf(" are the same\n");
   else
      printf(" are different\n");
   if (r_strcmp(word1,word2) < 0)
      printf("  \"%s\" precedes \"%s\"\n",word1,word2);
   else if (r_strcmp(word1,word2) > 0)
      printf("  \"%s\" follows \"%s\"\n",word1,word2);
   else
      printf("  \"%s\" equals \"%s\"\n",word1,word2);

   return 0;
}

int r_strlen (const char *s)
{
   return ( *s == '\0' ? 0 : 1 + r_strlen(s+1) );
}

int strequ (const char *s1, const char *s2)
{
   if (*s1 != *s2)
      return 0;
   else if (*s1 == '\0')  /* implies *s2 == '\0' */
      return 1;
   else
      return strequ(s1+1,s2+1);
}

int r_strcmp (const char *s1, const char *s2)
{
   if (*s1 != *s2)
      return (*s1 - *s2);      /* arithmetic with ASCII codes */
   else if (*s1 == '\0')
      return 0;                /* both strings are equal */
   else
      return r_strcmp(s1+1,s2+1);
}