Exercise 5-3 (strcat - String concatenation, pointer version)

Chapter_5     Exercise_5-2     strcmp Exercise_5-4







Exercise 5-3     K&R, p. 107


Exercise 5-3. Write a pointer version of the function strcat() that we showed in Chapter_2; strcat(s,t) copies the string t to the end of s.




strcat.c     K&R, p. 48         download


#include <stdio.h> // for printf(), scanf()
#include <string.h> // for strcpy()

#define SIZE 100 // array size

void strcat1(char*, char*);
void strcat2(char*, char*);

int main()
{
char s1[SIZE*2], s2[SIZE*2], t[SIZE];

printf("Type a word: ");
scanf("%s", s1);
printf("Type another word: ");
scanf("%s", t);

printf("strcat1(%s, %s): ", s1, t);
strcpy(s2,s1);// save old s1
strcat1(s1,t); // only s1 changes
printf("%s\n", s1);
printf("strcat2(%s, %s): ", s2, t);
strcat2(s2,t); // only s2 changes
printf("%s\n", s2);

return 0;
}
// concatenate t to the end of s; s must be big enough
void strcat1(char *s, char *t)
{
int i = 0, j = 0;
// find the end of s:
while (s[i]) // while (s[i] != '\0')
{i++;}

while (s[i] = t[j]) // while((s[i] = t[j]) != '\0')
{i++, j++;} // copy ending '\0', then exit
}
// concatenate t to the end of s; s must be big enough
void strcat2(char *s, char *t)
{
// find the end of s:
while (*s) // while (*s != '\0')
{s++;}

while (*s++ = *t++) // while ((*s++ = *t++) != '\0')
{} // copy ending '\0', then exit
}
/*
gcc strcat.c -o strcat
./strcat
Type a word: hocus-
Type another word: pocus
strcat1(hocus-, pocus): hocus-pocus
strcat2(hocus-, pocus): hocus-pocus
*/





Note:  See also strcat in Chapter_2.









Chapter_5     Exercise_5-2     strcmp BACK_TO_TOP Exercise_5-4



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo