Code:
#include <stdio.h>
#include <string.h>
#define N 100
int stringcount(const char *string, const char *one);
void replace(const char *string, const char *one, const char *two, char *string2, int comp);
int compare(const char *one, const char *two);
main()
{
char string[N+1]={'\0'}, stringwhole[N+1]={'\0'}, word1[N+1]={'\0'}, word2[N+1]={'\0'};
char string2[N+1]={'\0'};
int number, i, comp;
printf("Input a line with at least two words:\n");
scanf("%s", word1);
scanf("%s", word2);
gets(string);
strcat(stringwhole, word1);
for(i=0; stringwhole[i]!='\0'; i++)
{}
stringwhole[i]=' ';
strcat(stringwhole, word2);
strcat(stringwhole, string);
number = stringcount(stringwhole, word1);
comp = compare(word1, word2);
printf("The number of occurrences of the first word %s is %d\n", word1, number);
replace(stringwhole, word1, word2, string2, comp);
puts(string2);
return 0;
}
int stringcount(const char *string, const char *one)
{
{int i,n,m;
int count = 0;
for(i=0; i<N; i++)
if(one[0] == string[i]){
for(n=0, m=i; one[n]!='\0' ; n++, m++)
{
if( one[n] == string[m])
{if(string[m+1]=='\0' || string[m+1]==' ')
count++;}
else if(one[n] != string[m])
continue;
}
}
return count;
}
}
void replace(const char *string, const char *one, const char *two, char *string2, int comp)
{
int i,j,n=0,m,q=0;
for(i=0; i<N; i++)
{
if(string[i] == one[0])
{
for(n=0, m=i; one[n]!='\0'; n++, m++)
{
if(one[n] == string[m])
{
if(string[m+1]==' ' || string[m+1]=='\0')
{
for(j=0; two[j]!='\0'; j++)
{
string2[q]=two[j];
q++;
}
}
}
}
if(two[j]=='\0')
{
if(comp>=0)
{
i+=m;
}
if(comp<0)
{
i=m;
}
}
}
string2[q] = string[i];
q++;
}
}
int compare(const char *one, const char *two)
{
int i, j;
for(i=0; one[i]!='\0'; i++)
{}
for(j=0; two[j]!='\0'; j++)
{}
if(i<j)
return 1;
if(i=j)
return 0;
if(i>j)
return -1;
}