In this exercise I am using Visual Studio 2019 and a modified version of the std_lib_facilities header
found here.
Chapter 20 // Exercise 6
Write a find-and-replace operation for Documents based on section 20.6.2
It's been so long since I read this chapter I forgot about the second half and had to re-read it.
Then I did some unreal stuff for a month, forgot again and had to re-read it again...
To say I procrastinated is an understatement. This exercise involves getting the code from section 20.6.2 to run. This means you need to write the match() function on page 740. Once you've done that you're halfway there as you have a way to find a word.
Match() is trivial. Since we have a string and iterators to the start and end of the document, we just loop through the string checking if the contents of the iterator matches each character, advancing the iterator each time round. If we get to the end of the string without returning false, we've found a match.
So that takes care of "find". To "replace", I got a reference to the vector of characters (the line) from the iterator. Worked out at what index the iterator was at by using this:
Then erased the characters from the vector and inserted the new ones.
So that was my first iteration of FindAndReplace(). It's great for finding and replacing individual words and sentences but not sequences of letters that can't be considered words like the example he gives in the chapter (ones containing special characters like secret\nhomestead). This one is a bit trickier. Let's say I have the lines:
"This is a line ending with a secret"
"homestead is a word."
We can return an iterator to point at the start of secret as finding the string "secret\nhomestead" is easy using match(). However, how would the text editor replace this? Remove secret, replace it with the word and remove homestead. Or remove secret and replace homestead with the word. Or even merging the two lines together with the replacement word?
I decided to go with the last one and merge the lines together; deleting any lines as necessary.
One thing I haven't allowed is the replacement string to insert new lines. So if you want to replace "banana" with "banana\napple" it won't insert a new line. But cout will make it look like a new line has been inserted. I may do that later.
Whilst doing Chapter 26 - Exercise 7. It asks to create tests for this code. So I got the code off github and found it no longer compiles. I'm guessing they've updated iterator standards over the past few years and it now requires you to have certain features defined. Either way std::find() would no longer work for the iterator class as defined in the book, so I re-wrote the find_text to not use std::find(). You can find that code here: