Program 36) 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 variable s3. At the end, the program should print the contents of all the three variables and their lengths.
In this program,during the first run, the input strings are "New" and "York". These strings are compared by the statement
x = strcmp (s1, s2) ;
Since they are equal, they are joined together and copied into s3 using statement
strpy (s3, s1) ;
The program outputs all the three strings with their lengths.
During the second run, the two strings s1 and s2 are equal, and therefore, they are not joined together. In this case all the three strings contain the same string constant "London"
PROGRAM
#include <string.h>
main ( )
{
char s1 [20], s2 [20], s3 [20] ;
int x, 11, 12, 13 ;
printf (" \n\nEnter two string constant \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 = strln (s1) ;
l2 = strln (s2) ;
l3 = strln (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) ;
}
Output: Enter two string constants
? New York
Strings are not equal
s1 = NewYork length = 7 characters
s2 = York length = 4 charcaters
s3 = NewYork length = 7 characters
Enter two string constants
? London London
Strings are equal
s1 = London length = 6 charcaters
s2 = London length = 6 characters
s3 = London length = 6 characters
No comments:
Post a Comment