In: Computer Science
please answer with coding from The second edition C programming language textbook
/* Changes all occurrences of t in s to u, result stored in v
*
* Example:
*
* char v[100];
* replace("hello", "el", "abc", v) => v becomes "habclo"
* replace("", "el", "abc", v) => v becomes "" (no change)
* replace("hello", "abc", "def", v) => v becomes "hello" (no change)
* replace("utilities", "ti", "def", v) => v becomes "udeflidefes"
*
*/
void replace(char *s, char *t, char *u, char *v)
{
}
void replace(char *s, char *t, char *u, char *v)
{
int flag,len=strlen(t);
for(int i=0;s[i]!='\0';i++)
{
if (strncmp(s+i,t,len) == 0)
{
strcat(v,u);
i=i+len-1;
continue;
}
strncat(v,s+i,1);
}
printf("%s\n",v); //you can omit this line if you don't need it,I did it to print the result
}
Here is the full code , if you need
#include<stdio.h>
#include<string.h>
void replace(char *s, char *t, char *u, char *v)
{
int flag,len=strlen(t);
for(int i=0;s[i]!='\0';i++)
{
if (strncmp(s+i,t,len) == 0)
{
strcat(v,u);
i=i+len-1;
continue;
}
strncat(v,s+i,1);
}
printf("%s\n",v);
}
int main()
{
char s[]="utilities";
char t[]="ti";
char u[]="def";
char v[100]={0};
replace(s,t,u,v);
return 0;
}