Program:
#include<stdio.h>
#include<string.h>
main()
{
char str[40],newstr[20],substr[20];
int len1,len2,i,j,k,t=0,len3,d=0;
printf("Enter the string:");
gets(str);
printf("Enter the substring:");
gets(substr);
printf("Enter the new string:");
gets(newstr);
len1 = strlen(str);
len2 = strlen(substr);
len3 = strlen(newstr);
for(i=0;i<len1;i++)
{
for(j=t=0,k=i;j<len2;j++,k++)
{
if(str[k]==substr[j])
t++;
else
break;
}
if(t==len2)
break;
}
if(t==len2)
{
printf("\nThe substring is found.\n");
printf("String replaced...\n");
if(len3>len2)
{
for(j=len1;j>=k;j--)
str[j+len3-len2] = str[j];
}
else
{
for(j=k;j<=len1;j++)
str[j-(len2-len3)] = str[j];
}
while(newstr[d]!='\0')
{
str[i] = newstr[d];
i++;
d++;
}
puts(str);
}
else
{
printf("\nSubstring not found.\n");
}
}
Output:
nn@linuxmint ~ $ gcc c18.c
/tmp/ccqnIqKS.o: In function `main':
c18.c:(.text+0x40): warning: the `gets' function is dangerous and should not be used.
nn@linuxmint ~ $ ./a.out
Enter the string:good night
Enter the substring:night
Enter the new string:morning
The substring is found.
String replaced...
good morning
nn@linuxmint ~ $
#include<stdio.h>
#include<string.h>
main()
{
char str[40],newstr[20],substr[20];
int len1,len2,i,j,k,t=0,len3,d=0;
printf("Enter the string:");
gets(str);
printf("Enter the substring:");
gets(substr);
printf("Enter the new string:");
gets(newstr);
len1 = strlen(str);
len2 = strlen(substr);
len3 = strlen(newstr);
for(i=0;i<len1;i++)
{
for(j=t=0,k=i;j<len2;j++,k++)
{
if(str[k]==substr[j])
t++;
else
break;
}
if(t==len2)
break;
}
if(t==len2)
{
printf("\nThe substring is found.\n");
printf("String replaced...\n");
if(len3>len2)
{
for(j=len1;j>=k;j--)
str[j+len3-len2] = str[j];
}
else
{
for(j=k;j<=len1;j++)
str[j-(len2-len3)] = str[j];
}
while(newstr[d]!='\0')
{
str[i] = newstr[d];
i++;
d++;
}
puts(str);
}
else
{
printf("\nSubstring not found.\n");
}
}
Output:
nn@linuxmint ~ $ gcc c18.c
/tmp/ccqnIqKS.o: In function `main':
c18.c:(.text+0x40): warning: the `gets' function is dangerous and should not be used.
nn@linuxmint ~ $ ./a.out
Enter the string:good night
Enter the substring:night
Enter the new string:morning
The substring is found.
String replaced...
good morning
nn@linuxmint ~ $
0 comments:
Post a Comment