String Manipulations using C

C Program :

/* Aim: Write a menu driven program to perform different6 operations on strings. Write seperate functions for each option.
1] Check if one string is substring of another
2] Count number of occurences of character in string
3] Replace all occurences of a character by another
*/
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#define size 100
void subStrCheck(char str[],char subStr[]); // subStrCheck Function Prototype
int CheckStr(char str[],char ch); // CheckStr Function Prototype
void replaceStr_Ch(char str[],char ch,char ch1); // replaceStr_Ch Function Prototype
void main()
{
char str[size],subStr[size],ch,ch1;
int ch2;
do{
printf("\n \t \t ****Menu****");
printf("\n 1.Check if one string is substring of another");
printf("\n 2.Count number of occurences of character in string");
printf("\n 3.Replace all occurences of a character by another");
printf("\n 4.Exit \n");
printf("\n Which operation do you want to perform:-");
scanf("%d",&ch2);
if(ch2==2 || ch2==3)
{
printf("\n Enter any string:-");
scanf("%s",str);
printf("\n Enter any character to check its occurence in the string:-");
scanf(" %c",&ch);
}
switch(ch2)
{
case 1:
printf("\n Enter any string:-");
scanf("%s",str);
printf("\n Enter string to check as substring in \"%s\":-",str);
scanf("%s",subStr);
subStrCheck(str,subStr);
break;
case 2:
printf("\n %d times '%c' occured in \"%s\" \n \n",CheckStr(str,ch),ch,str);
break;
case 3:
printf("\n Enter a character to replace '%c' in \"%s\":-",ch,str);
scanf(" %c",&ch1);
replaceStr_Ch(str,ch,ch1);
break;
default:
printf("\n Invalid Choice. \n \n");
}}while(ch2!=4);
} // End of main
void subStrCheck(char str[],char subStr[])
{
int LED=0,i,j,count=1,count1=1;
for(i=0;str[i]!='\0';i++)
count++;
for(i=0;subStr[i]!='\0';i++)
count1++;
for(i=0;i<=count-count1;i++)
{
for(j=i;j<i+count1;j++)
{
LED=1;
if(str[j]!=subStr[j-i])
{
LED=0;
break;
}
}
if(LED==1)
break;
}
if(LED==1)
printf("\n \"%s\" is a substring of \"%s\" \n \n",subStr,str);
else
printf("\n \"%s\" is not a substring of \"%s\" \n \n",subStr,str);
}
// CheckStr Function
int CheckStr(char str[],char ch)
{
int i,count=0;
for(i=0;i<=strlen(str)-1;i++)
{
if(str[i]==ch)
count++;
}
return count;
}
// replaceStr_Ch Function
void replaceStr_Ch(char str[],char ch,char ch1)
{
int i,count=0;
for(i=0;i<=strlen(str)-1;i++)
{
if(str[i]==ch)
str[i]=ch1;
}
printf("\n New string formed after replacing '%c' with '%c' is \"%s\" \n \n",ch,ch1,str);
}
/* Ouput of above code:-
[root@localhost Computer Science C]# cc e12b1.c
[root@localhost Computer Science C]# ./a.out
****Menu****
1.Check if one string is substring of another
2.Count number of occurences of character in string
3.Replace all occurences of a character by another
4.Exit
Which operation do you want to perform:-1
Enter any string:-Hello
Enter string to check as substring in "Hello":-lo
"lo" is a substring of "Hello"
*/
view raw OpeStr.c hosted with ❤ by GitHub
Get This Program: