Saturday, 3 January 2015

Custom concatenation function in C programming.

If you ever used strcat function in C / C++ you know it is a function which is used to concatenate 2 string.

Now suppose I want to concatenate 2 string Subhroneel and Ganguly. Now when we concatenate these 2 string output is SubhroneelGanguly, it is really irritating, so strcat return the concatenate string so that we can use it in a nested fashion. i.e. strcat(strcat("Subhroneel," "),"Ganguly"), so we get the output as Subhroneel Ganguly. We may have given a space before Ganguly that might have solve the problem but the really objective is to show how to concatenate more than 2 string within a single line, this is possible only because strcat returns the concatenate string after concatenating with target string.
I have written the concatenate function in small C program. Just go through this and see how concatenate function works.

#include<stdio.h>
#include<conio.h>

char *strconcat(char *target,char *source)
{
    char *head=target;
/*  Copied the head address of target string into head pointer this will help us to return the target string after concatenation.*/

    while(*++target);
/*  Moved the pointer to the end of the string (NULL) while(NULL) is false. Pre increment is used so that target pointer does not get incremented after reaching NULL. */

    while(*source)  // looped until source string reaches NULL
        *target++=*source++;   // Copying each element and then incrementing both.

    *target=NULL;  // Set target to NULL as while loop exits while reaching NULL for source.

    return head; // returning the entire string.
}

void main()
{
    char sourcestring[50],targetstring[100];

    printf("\nEnter first string : ");

    gets(targetstring);  // Target string

    printf("\nEnter second string : ");

    gets(sourcestring); // Source String



   // Just look carefully to the function call strconcat is called twice in a nested form. First one returning i.e. "Subhroneel " and then second one "Subhroneel Ganguly"

    printf("\nConcated string : %s",strconcat(strconcat(targetstring," "),sourcestring));

    getch();
}

No comments: