Wednesday, March 2, 2011

Character Arrays and Strings

s1,s2 and s3 are three string variables. Write a program to read two string constants into s1 and s2 and compare whether they are equal or not. If they are not , join them together. Then copy the contents of s1 to the variables s3. At the end, the program should print the contents of all the three variables and their lengths.

#include <stdio.h>
#include <string.h>
void main()
   {   char  s1[20], s2[20], s3[20];
       int   x, l1, l2, l3;                                   
       printf("\n\nEnter two string constants \n");           
       printf("?");                                           
       scanf("%s %s", s1, s2);                                
    /* comparing s1 and s2 */                                 
       x = strcmp(s1, s2);                                    
       if(x != 0)                                             
       {   printf("\n\nStrings are not equal \n");            
           strcat(s1, s2);   /* joining s1 and s2 */          
       }                                                      
       else                                                   
           printf("\n\nStrings are equal \n");                
   /* copying s1 to s3 */
       strcpy(s3, s1);                                        
    /* Finding length of strings */                           
       l1 = strlen(s1);                                       
       l2 = strlen(s2);                                       
       l3 = strlen(s3);                                       
    /* output */                                              
       printf("\ns1 = %s\t length = %d characters\n", s1, l1);
       printf("s2 = %s\t length = %d characters\n", s2, l2);  
       printf("s3 = %s\t length = %d characters\n", s3, l3);  
       getch();
   }

OUTPUT
Enter two string constants
? New York
String are not equal
s1 = NewYork     length = 7 characters
s2 = York             length = 4 characters
s3 = NewYork     length = 7 characters

Enter two string constants
? London London
s1 = London     length = 6 characters
s2 = London     length = 6 characters
s3 = London     length = 6 characters

No comments:

Post a Comment