Hi,
I have text (string) and I want to find a given word (it's ok!) and then insert another given word after the first word.
The original string is beeing copied into a new string.
But something is going wrong!!!
Where is my mistake?
Thanks in advance...
(I have some patches...)
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//insert "new_word" after each occurence of "word"
int main(){
char A[100]="In the sentence words the and the.";
char B[200]="";
char *word="the";
char *new_word="com";
char *p;
int word_count=0;
int i,j,word_index;
int found,position;
i=0;
j=0;
found=0;
while(A[i]!='\0'){
word_index=0;
position=i;
while(A[i]==word[word_index]){//we found same letters
B[j]=A[i];//copy A to B letter by letter
printf("A[%d]=%c B[%d]=%c \n",i,A[i],j,B[j]);//getchar();
i++;j++;word_index++;//increment indices
printf("A[%d]=%c B[%d]=%c \n",i,A[i],j,B[j]);//getchar();
printf("A: %s\n",A);
printf("B: %s\n",B);
}
if (word_index==strlen(word)) {//word was found
found=1;
printf("position=%d\n",position);
printf("A[%d]=%c B[%d]=%c \n",i,A[i],j,B[j]);//getchar();
B[j]=' ';
j++;
strcat(B,new_word);//copy new_word to B[] after word
printf("A[%d]=%c B[%d]=%c \n",i,A[i],j,B[j]);//getchar();
printf("A: %s\n",A);
printf("B: %s\n",B);
j=j+strlen(new_word)+1;//increment j
B[j]=' ';
printf("A: %s\n",A);
printf("B: %s\n",B);
i++;j++;
continue;//exit while loop and continue parsing
}
else{
B[j]=A[i];//else continue copying A to B
printf("A[%d]=%c B[%d]=%c \n",i,A[i],j,B[j]);//getchar();
printf("A: %s\n",A);
printf("B: %s\n",B);
i++;j++;
}
}
if(!found) printf("\"%s\" not found!\n",word);
puts(A);
puts(B);
getchar();
return 0;
}