Concat two strings without using library functions

Lets see how we can concat a source string to the end of destination string without using library functions.

Code

#include<stdio.h>

int main() 
{
    char source[20],dest[20];
    int i,j;

    printf("\nEnter source string : ");
    gets(source);

    printf("\nEnter dest string : ");
    gets(dest);

    j = 0;

    while (dest[j] != '\0')              //j is positioned on NULL char of dest                  
            j++;                

    for (i=0;source[i]!='\0';i++,j++)   // Concat 
            dest[j] = source[i];

    dest[j] = '\0';

    printf("\nConcated string = %s",dest);

    return 0;
}

O/P



Code Tracing

dest[]                                source[]         

            j                        i
S t r i n g \0                       P r o g r a m
                        j 
S t r i n g P r o g r a m
                          j
S t r i n g P r o g r a m \0

Lets see how we can concat two strings using pointers.
#include<stdio.h>

int main() 
{
    char source[20],dest[20];
    char *i,*j;

    printf("\nEnter source string : ");
    gets(source);

    printf("\nEnter dest string : ");
    gets(dest);

    j = dest;

    while (*j != '\0')                         //j points to NULL char of dest                  
            j++;                

    for (i=source;*i!='\0';i++,j++)            //concat
            *j = *i;

    *j = '\0';

    printf("\nConcated string = %s",dest);

    return 0;
}

No comments:

Post a Comment