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, lname;
printf("Enter your first name: ");
printf("Enter your last name: ");
strcat(full_name, " ");
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