C Program to Find Total of Even Integers

String Handling Function in C Programming

C program provides set of pre-defined functions called string handling functions to work with string values in programming. The string handling functions are defined in a header file called string.h.

For Example 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.


The C program is shown in below code with example. 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 not equal, they are joined together and copied into s3 using the statement

strcpy(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”.

Example: Simple String handling function

#include <string.h>
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);
}

Output result,

Enter two string constants
? New York
Strings are not equal
s1 = NewYork length = 7 characters
s2 = York length = 4 characters
s3 = NewYork length = 7 characters
Enter two string constants
? London London
Strings are equal
s1 = London length = 6 characters
s2 = London length = 6 characters
s3 = London length = 6 characters

Let me know if you find any difficulty in understanding this C Program with string handling function and I would be glad to explain it further.

Online Training Tutorials