Simple String Operations in C Language
Write a Simple String Operations program in C to perform String operations on strings using library functions
- Concatenate a string S3 to string S2.
- Copy a string S3 to another string S2.
- Find the length of a given string
- Compare two strings S2 and S3.
Simple String Operations Code
#include <stdio.h>
#include <string.h>
#include<conio.h>
#define MAXLEN 120
void main()
{
char string1[MAXLEN], string2[MAXLEN];
char result[MAXLEN];
int choice,activity;
int comparison;
clrscr();
while(1)
{
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: “);
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”);
scanf(“%d”, &activity);
switch(activity)
{
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);
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”);
}
}


Leave a Reply