Copying one string into another

Program 33) Write a program to copy one string into another and count the number of characters copied.

In this program, we use a for loop to copy the characters contained inside string2 into the string1. The loop is terminated when the null character is reached. Note that we are again assigning a null character to the string1.

                                    PROGRAM

main ( ) 
 {
       char string1 [80], string2 [80] ;
       int i ;
   
       printf ("Enter a string \n") ;
       printf ("?") ;


       scanf ("%s", string2) ;
       for (i = 0; string2 [i]  ! =  '\0'; i++) 
                  string1 [i] = string2 [i] ;
       string1 [i] = '\0' ;


       printf ("\n") ;
       printf ("%s\n", string1) ;
       printf ("Number of characters = %d\n", i) ;
 }


Output:      Enter a string
                  ?Manchester


                   Manchester
                   Number of characters = 10


                   Enter a string 
                   ?Westmminister

                   Westminister
                   Number of characters = 11


 

No comments:

Post a Comment