Objective

This code allows user to enter the string and manipulate the string using library functions.

Summary

In this String Operations in C program using c language we will ask user for string on which basic operations need to be performed. Program will run with he menu options such as :

  • Enter String
  • Concatenate Strings
  • Find length of Strings
  • Compare Strings
  • Copy String to another one
  • Display String

String Operations in C

String Operations in C Program

 

/* Write a program in C to carry out following operations on strings using library functions
a. To concatenate a string S2 to string S1.
b. To find the length of a given string
c. To compare two strings S1 and S2.
d. To copy a string S2 to another string S1. */

#include < stdio.h > #include < string.h > #include < conio.h > #define MAXLEN 128
void main() {
char string1[MAXLEN], string2[MAXLEN]; /* strings where user input is stored */
char result[MAXLEN]; /* string where result is stored */
int choice, act;
int comparison;
clrscr();
while (1) {
/* Display a message that we need to desired operation*/
printf(“Enter your choice: \n”);

printf(“1. Enter the strings\ n”);
printf(“2. To concatenate a string S2 to string S1\ n”);
printf(“3. To find the length of a given string\ n”);
printf(“4. To compare two strings S1 and S2.\n”);
printf(“5. To copy a string S2 to another string S1.\n”);
printf(“6. Display S1 and S2.\n”);
printf(“0. Exit\ n\ n”);
printf(“Your Choice: “);
/* Read user’s choice into act */
scanf(” % d”, & choice);

switch (choice) {
case 1:
printf(“Please enter first string(maximum length % d)\ n”, MAXLEN– 1);
flushall();
gets(string1);

printf(“Please enter second string(maximum length % d)\ n”, MAXLEN– 1);
flushall();
gets(string2);
break;
case 2:
strcat(string1, string2);
printf(“S1 now is: \n % s\ n”, string1);

break;
case 3:
printf(“Please select a string to find length of \n”);

printf(“1. S1\ n”);
printf(“2. S2\ n”);
printf(“3. New string\ n”);

/* Read user’s choice into act */
scanf(” % d”, & act);

switch (act) {
case 1:
printf(“The length is % d\ n”, strlen(string1));
break;
case 2:
printf(“The length is % d\ n”, strlen(string2));
break;
case 3:
printf(“Please enter new string(maximum length % d)\ n”, MAXLEN– 1);
scanf(” % s”, result);
printf(“The length is % d\ n”, strlen(result));
break;
}
break;
case 4:
comparison = strcmp(string1, string2);

if (comparison == 0) {
printf(“S1 is lexicographically equal to S2\ n”);

} else if (comparison < 0) {
printf(“S1 is lexicographically smaller than S2\ n”);

} else {
printf(“S1 is lexicographically greater than S2\ n”);

}
break;
case 5:
strcpy(string1, string2);

/* Display the result*/
printf(“S1 is now: \n % s\ n”, string1);

break;
case 6:
printf(“S1 is now: \n % s\ n”, string1);
printf(“S2 is now: \n % s\ n”, string2);
break;
case 0:
exit();

}
printf(“\n\ n”);
}
}