Putting Strings Together


Just as we cannot assign one string to another directly, we cannot join two strings together by the simpe arithmetic addition. That is, the statements such

str3 = str1 + str2;

are not valid. The characters from str1 and str2 should be copied into str3 one after the other. The size of the array str3 should be large enough to hold the characters.

The process of merging two strings together is called concentration. The programs depict a combination of three strings.

Sample Program

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

    int main() {
      char fn[10] = "chandan";
      char mn[10] = "kumar";
      char ln[10] = "payra";
      int i,j,k;
      char fullName[30];
      
      for(i=0;fn[i]!='\0';i++)
       fullName[i] = fn[i];
      fullName[i] = ' ';
      
      for(j=0;mn[j]!='\0';j++)
       fullName[i+j+1] = mn[j];
      fullName[i+j+1]=' ';
      
      for(k=0;ln[k]!='\0';k++)
       fullName[i+j+k+2] = ln[k];
      
      /* printf fullName */
      printf("%s",fullName);
      return 0;
    }
    

The names of employees of an organization are store in three arrays, namely fn, mn, and ln. Write a program to concatenate the three parts into one string to be called fullName.

The program is given Three for loops are used to copy the three strings. In the first loop, the characters contained in the fn are copied into the variable fullName until the null character is reached. The null character is not copied; instead it is replaced by a space by the assignment statement

fullName[i] = ' ';

Similarly, the mn is copied into fullName, starting from the column just after the space created by the above statement. This is achieved by the assignment statement

fullName[i+j+1] = mn[j];

If fn contains 7 characters, then the value of i at this point will be 7 and therefore the first character from mn will be placed in the fifth cell of fullName. Note that we have stored a space in the fourth cell. In the same way, the statement

fullName[i+j+k+2] = ln[k];

is used to copy the characters from ln into the proper locations of fullName.

At the end, we place a null character to terminate the concatenated string fullName.