/**********************************************
* CP-I Warmup 1999-2000
* Problem #11
*********************************************/
/*
* Question:
*
* Your program takes a sentence (terminated by '\n') and two additional
* words, word1 and word2 as input. You are required to write a program
* in C that will replace every occurrence of word1 in the sentence by
* word2. The program should display the new sentence, the number of
* words replaced in the sentence and the column number where word1
* occured in the original sentence. If no occurrence of word1 is found
* in the sentence, a suitable message should be displayed.
*
* You can assume that the length of word1 is equal to the length of word2.
* You can also assume that the input is in lowercase letters.
*
* Ex:
* Input:
* this is my old gold book
* old
* new
* Output:
* this is my new gnew book
* The number of replacements: 2
* Columns: 12 17
*/
#include <stdio.h>
#include <string.h>
#define MAX_STRING_LENGTH 100
#define MAX_WORD_LENGTH 20
#define MAX_NO_OF_REPLACEMENTS 20
main()
{
char str[MAX_STRING_LENGTH];
char old[MAX_WORD_LENGTH],new[MAX_WORD_LENGTH];
char *temp;
int col[MAX_NO_OF_REPLACEMENTS]={0},count;
int i;
printf("Give the string: \n");
scanf("%[^\n]",str);
printf("Word to replace: ");
scanf("%s",old);
printf("Replace with: ");
scanf("%s",new);
temp=str;
count=0;
while(temp=strstr(temp,old))
{
col[count++]=temp-str+1;
strncpy(temp,new,strlen(new));
temp+=strlen(new);
}
if(count)
{
printf("New String: \n%s\n",str);
printf("The number of replacements: %d\n",count);
printf("Columns:");
for(i=0;i<count;i++)
printf("%d\t",col[i]);
printf("\n");
}
else
printf("No occurences of %s were found\n",old);
}