< Prev
Next >



C++ strcat() function




The strcat() is a string manipulation function defined in the string.h header file, which works on a string which is stored in a c-style char array. This function 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<iostream>
#include<cstring>

using namespace std;

int main()
{
char dest[10] = "Hello";
char src[10] = "World";
cout<<"The value in destination string : " <<dest << "\n";
cout<<"The second in source string : " <<src << "\n";

strcat(dest,src);
cout<<"Concatenated strings : " << dest;

return 0;
}


Output is -


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






  • 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<iostream>
    #include<cstring>
    
    using namespace std;
    
    int main()
    {
    char dest[20] = "Hello";
    char src[10] = "World";
    
    cout<< "The value in dest string : " << dest << "\n";
    cout<< "The second in src string : " << src << "\n";
    
    int len1 = strlen(dest);
    int len2 = strlen(src);
    
    cout<< "Length of characters in dest string : " << len1 << "\n";
    cout<< "Length of characters in src string : " << len2 << "\n";
    
    for(int i=0;i<len2; i++)
    {
    	dest[len1] = src[i];
    	len1 = len1 + 1 ;
    }
    dest[len1]='\0';
    
    cout<< "Concatenated strings : " << 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 -

    Facebook Google Pinterest Reddit Tumblr Twitter




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

    Please Subscribe

    Please subscribe to our social media channels for daily updates.


    Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page

    Notifications



    COMING SOON
    -
    PYTHON