S07 Answer


/* Puzzle S07 -- string concatenation */

#include <stdio.h>
#include <stdlib.h>

void stringCopy( char *copy, char *source )
{
  while ( *copy++ = *source++ ) ;
}

char *stringConcat( char *s1, char *s2 )
{
  char *p = s1;         /* save for return value */

  while ( *s1 ) s1++ ;  /* advance s1 to the null */

  stringCopy( s1, s2 ); /* copy s2 to the end */
  return s1;
}

int main(int argc, char *argv[])
{
  char buffer[ 100 ];
  char *trialsA[] =
  {
  "The game is",
  "Genius is an infinite capacity",
  "So is",
  "",
  "As always,\n",
  "Will\ttabs\t",
  "For great fun, "
  };

  char *trialsB[] =
  {
  " afoot!",
  " for taking pains.",
  " programming.",
  "concatenated to an empty string",
  "linefeeds should\nwork.",
  "confuse\tthings?",
  " change the buffer size to 5!"
  };

  int j ;
  for ( j=0; j<sizeof(trialsA)/sizeof(char *); j++ )
  {
    stringCopy( buffer, trialsA[j] );
    stringConcat( buffer, trialsB[j] );
    printf("%s\n", buffer );
  }

  system("PAUSE");
  return 0;
}

Comments: