Searching for substrings within a file

I am currently working on an assignment for my CS1 class and need help. We are to write a program that reads three files, one which serves as a master text file, one with a list of search words, and another with a list of replacement phrases. The program must then find the search words within the master text file using substrings and replace them with the substitute phrases. So far, i have read the search words and replacement phrases into separate, single dimension arrays (NOTE: we are not permitted to use vectors) but, i am now stuck as to how to go about finding each substring and replacing it with the substitute phrase.

So far, this is what i have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	
while(!file3.eof()){                  //where file3 is the master text file
	getline(file3, scriptstring);
	for (int k = 0; k < count1; k++){
		bool test = true;
		if(scriptstring.find(searchword[k])){
			scriptstring = scriptstring.replace(scriptstring.find(searchword[k]), searchword[k].size(), substitute[k]);		
			counter++;
		}
		if(!scriptstring.find(searchword[k])){
				test = false;
				break;
		}
	}
	cout << scriptstring << endl;
}


I have never before used the find and replace functions. Thanks in advance fore the help
Last edited on
.find() either returns the start of the area or string::npos is the specificed string does not exist. You also don't need to set the string to the .replace(), replace will update the string for you. Other then that...it looks OK to me, except I don't see what the purpose of the test bool is.
OMG CHEATER!
i ended up sorta hard coding it so i would have each word be looked up and replaced individually and as it was replaced id have a counter for each word be updated. ...funny thing is that the TA said that it was a ligit solution that would be accepted.

but i also tried to do something like yours

f3/str3/count3 are for the script file
str1 / count 1 are for the search word file
str2 is for the replace word file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
while(!f3.eof()) {
    f3 >> str3[count3];
    count1 = 0;
 while(1){
      int pos = str3[count3].find(str1[count1]);
      if (pos == -1) {
	break;
      }
      str3[count3].replace(pos, str3[count3].size(), str2[count1]);    
    }
 cout << str3[count3] << " ";
    count3++;
    count1++;
}

i thought it made sense but ends up that the script file gets mutilated....the first half is missing and words are cut up.
yea so id appreciate any help as well...by 11:59 PM eastern time.
Last edited on
I would stick with getline to get stuff you the file, since I am pretty sure that f3 >> str3[count3] will just put the whole file into that part of the array. Anyway, I think str.replace will only replace the area where you are trying to replace stuff, so if you try to replace a 4 letter word with "random" you will get "rand" in that space. I would go back to using .find() .erase() and .insert().
Topic archived. No new replies allowed.