by Dinesh Thakur Category: Function and Pointer

String concatenation is another basic string manipulation operation. In this, all the characters in a string, including the null terminator, are appended to the target string (i. e., copied at the end) replacing the null terminator in it. Thus, after the concatenation operation, the target string contains all the characters originally contained in it followed by those in the appended string. For example, if string sl contains "Pine" and string s2 contains "apple", then appending string s2 to sl modifies string sl to "Pineapple". Note that sl must have enough character positions to accommodate all the appended characters, including the null terminator.

We cannot use the += operator to append a string to another string, as in str2 += strl. Instead, the C standard library provides the strcat and strncat functions to concatenate strings. The strcat function concatenates an entire string to the target string. The strncat function, on the other hand, appends at the most n characters.

A typical call to the strcat function, which is similar to the strcpy function call, is as follows:

strcat (dest , src) ;

This function appends string src to dest and returns a pointer to string dest, which is usually ignored.

Example of concatenate String

The program segment given below accepts the user's first name and last name and concatenates them to construct a string containing his/her full name.

char fname[20], lname[20];

char full_name[40];

printf("Enter your first name: ");


printf("Enter your last name: ");

gets (lname);

strcpy(full_name, fname);

strcat(full_name, " ");

strcat(full_name, lname);

printf("Your full name: %s\n", full_name);

The character arrays fname,lname and full_name are used to store the first name, last name and full name of a person.Note that the first and lastnames can eachhave at most 19 characters. Thus, 40 charactersreserved for full name are adequate for the concatenated string (19 x 2 for names+ 1 space+ null terminator).

Initially, the gets functions read the user's first and last names from the keyboard. Then the strcpy function is used to copy the first name to full_name followed by two calls to the strcat function to append a space and last name to full name. The output of this code segmentis given below.

Enter your first name: Dinesh

Enter your last name: Thakur

Your full name: Dinesh Thakur


About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles