write a program to enter a string "Dhoni is better than sachin" .Replace dhoni with sachin and sachin with dhoni .... without using string replace function
Answers
I have written a generic program.. so it works.
#include <stdio.h>
#include <string.h>
int main(void) {
char str[128]=" ", word1[100]=" ", word2[100]=" ", *w1, *w2;
char outp[128]=" "; int i, j,k, n, n1, n2, pos1=-1, pos2=-1 ;
printf("Input string : "); gets(str);
printf("\ninput the first word : "); gets(word1);
printf("\ninput the 2nd word: "); gets(word2);
n = strlen(&str[0]); n1 = strlen(&word1[0]); n2 = strlen(&word2[0]);
w1 = &word1[0] ; w2= &word2[0];
for (i=0; i< n ; i++) { // find position of word1
for (j=0; i+j < n && j < n1 && str[i+j] == w1[j]; j++) ;
if (j == n1) {pos1 = i; break;}
}
for (i =0; i < n; i++) { // find position of word2
for (k=0; i+k < n && k < n2 && str[i+k] == w2[k] ; k++) ;
if (k == n2) {pos2 = i; break;}
}
if (pos1 >=0 && pos2 >=0) { // both words r there. replace words.
if (pos2 < pos1) { // make pos1 smaller , interchange
int temp = pos1; pos1 = pos2; pos2 = temp;
temp = n1 ; n1 = n2; n2 = temp;
char *t = w1; w1 = w2; w2 = t;
}
for (i =0; i < pos1; i++) outp[i] = str[i];
for (j=0; j < n2; j++, i++) outp[i] = w2[j];
for (j=pos1+n1; j < pos2 ; j++, i++) outp[i] = str[j];
for (j=0; j < n1 ; j++, i++) outp[i] = w1[j];
for (j=pos2+n2 ; j < n; j++, i++) outp[i] = str[j] ;
outp[i]= '\0';
} // if
printf("\n:inp string : %s\n words: %s :: %s\n outp string: %s\n", str, word1, word2, outp);
return 0;
}