Concatenation of string

Program 35) The names of employees in an organization are stored in three arrays, namely first_name, second_name, and last_name. Write a program to concatenate the three parts into one string to be called name.

In this program, three for loops are used to copy the three strings. In the first loop, the character contained in the first_name are copied into the variable name until the null character  is reached. The null character is not copied; instead it is replaced by a space by the assignment statement
                                     name [i] = ' ' ;
Similarly, the second _name is copied into name, starting from the column just after the space created by the above statement. This is achieved by the assignment statement
                           name [i + j + 1] = Second_name [j] ;
If first_name contains 4 characters then the value of i at this point will be 4 and therefore the first character from second_name will be placed in the fifth cell of name. Note that we have stored a space in the fourth cell.
In the same way, the statement                                                                      name [i + j + k + 2] = last_name [k] ;
is used to copy the characters from last_name into the proper location of name. In this example, it is important to note the use of the expressions i + j + 1 and i + j + k +2


                                   PROGRAM

main ( )
 {
       int i, j, k ;
       char first_name [10] = {"VISWANATH"} ;
       char second_name [10] = {"PRATAP"} ;
       char last_name [10] = {"SINGH"} ;
       char name [30] ;
     /*  Copy first_name into name  */
       for (i = 0; first_name [i] ! =  '\0' ; i++)
            name [i] = first name [i] ;
   
   /*   End first name with a space  */
         
      name [i] = ' ' ;
   
  /*  Copy second_name into name  */
         
      for (j = 0; second_name [j]  ! =  '\0'  ; i++)
              name [i + j + 1] = second_name [j] ;
  
  /*  End second_name with a space  */
         
      name [i + j +1] = ' ' ;
  
 /*   Copy last_name into name  */
        
     for (k = 0; last_name [k]  ! =  '\0' ; k++)
              name [i+ j + k + 2] = '\0' ;
              printf ("\n\n") ;
              printf ("%s \n", name) ;
 }

Output:      VISHWANATH  PRATAP  SINGH

No comments:

Post a Comment