Advertisement



< Prev
Next >



C strcat() method




The strcat() is a string function defined in the string.h header file, which is used to add or concatenate two strings by appending a string at the end of another string.




Signature of strcat() function


char * strcat ( char * destination, const char * source )







Example of strcat() function


In the upcoming code, we are calling strcat() function, to add the content of one string named src at the end of characters present in another string named dest, both string values are contained in a char[] array and are passed as a parameter to the strcat() function.

/*  Program to concatenate values in two char array with string values */

#include<string.h>
#include<stdio.h>

int main()
{
char dest[10] = "Hello";
char src[10] = "World";
printf("The value in destination string : %s", dest);
printf("\n");

printf("The second in source string : %s", src);
printf("\n");

strcat(dest,src);
printf("Concatenated strings : %s ", dest);

return 0;
}


Output is -


First  String value : Hello
Second String value : World
Concatenated strings : HelloWorld




Advertisement




  • Adding two strings without using strcat()


  • Let's create a program which appends the characters in one string at the end of another string without using strcat() function.


    /* Program to append one string at the end of another string withut strcat() function */
    
    
    #include<string.h>
    #include<stdio.h>
    
    int main()
    {
    char dest[20] = "Hello";
    char src[10] = "World";
    
    printf("The value in dest string : %s", dest);
    printf("\n");
    
    printf("The second in src string : %s", src);
    printf("\n");
    
    int len1 = strlen(dest);
    int len2 = strlen(src);
    
    printf("Length of characters in dest string : %d \n", len1);
    printf("Length of characters in src string : %d \n", len2);
    
    for(int i=0;i<len2; i++)
    {
    	dest[len1] = src[i];
    	len1 = len1 + 1 ;
    }
    dest[len1]='\0';
    
    printf("Concatenated strings : %s ", dest);
    
    return 0;
    }
    


    Output is :


    The value in dest string : Hello
    The second in src string : World
    Length of characters in dest string : 5
    Length of characters in src string : 5
    Concatenated strings : HelloWorld





    Note: - The function strlen returns the total number of characters actually present in the char[] and not the total number of character it can hold.





    Please share this article -





    < Prev
    Next >
    < C strlwr() function
    C strncat() function >



    Advertisement

    Please Subscribe

    Please subscribe to our social media channels for daily updates.


    Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




    Advertisement

    Notifications



    Please check our latest addition

    PYTHON


    Advertisement