Help needed with an exercise

I need some help to understand this exercise: "write a C++ code to replace all the words "dog" with "cat" from the following test: The quick brown fox jumps over the lazy dog.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
    string str;
    getline(cin, str);
    cout << "Original text: " << str;
          for (int j = 0; j < (int)str.size(); j++) {
              string key = str.substr(j, 3), repl;
               if (key == "fox") {
                   repl = "cat";
                   for (int k = 0; k < 3; k++) {
                       str[j+k] = repl[k];
                }
            }
        }
       cout <<"\nNew text: " << str << endl;


return 0;]>
I understand it for the most part except for the last one where "str[j+k] = repl[k];". I understand str[j+k] but can't get why it is = repl[k] because repl[k] = "cat". I'd appreciate if you help me understand it. Thanks in advance.
Last edited on
1
2
3
4
5
6
if (key == "fox") {  //if you found the word fox
repl = "cat";    //assign repl string the value "cat"
for (int k = 0; k < 3; k++) {  //loop for 3 letters
str[j+k] = repl[k];      //replace str[j], which is where you found "fox", with "cat".  
str[j+0] is the letter 'f' in fox, replaced with the letter 'c' in cat. then k becomes 1 in the loop
str[j+1] is the letter 'o' in fox, replaced with the letter 'a' in cat, then k becomes 2 ... etc


use the tools we have. look at the string functions find() and replace(). you can write this whole program in 3 lines (real lines of code, not counting variable creation etc). While this code shows you how to do it the hard way, it is better to use the build in functions which have already been debugged and are what other programmers expect to see. If you were asked to do it the hard way, then just be aware that there is a tool for this even as you figure it out.

also wrap code in <> tags from the little editor helper next time (not a big deal for first post).
Last edited on
I know that the code is done the hard way, but the point here is to learn and understand how the loops work, no matter how foolish and pointless.
Thanks for your answer but please elaborate. srt[j+k] makes a perfect sense but why do we assign str[j+k] = repl[k]? Isn't repl[k] the words c,a and t? Then why are we assigning them to the already complete str[j+k], which is the whole string with the new work? Why do we need the repl[k], which is the letters c,a,t?

Hello freenba2002,

Just to help you along:

PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

It makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.


Your slightly revised code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <iomanip>
#include <string>

int main()
{
	std::string str{ "The quick brown fox jumped over the lazy dog." };  //<--- Done this way for testing.

	//std::getline(std::cin, str);  // <--- Done this way for testing.

	std::cout << "Original text: " << str;

	for (int j = 0; j < static_cast<int>(str.size()); j++)
	{
		std::string key = str.substr(j, 3), repl;

		if (key == "fox")
		{
			repl = "cat";
			for (int k = 0; k < 3; k++)
			{
				str[j + k] = repl[k];
			}
		}
	}

	std::cout << "\nNew text: " << str << std::endl;

	return 0;
}

The first two lines in "main" are done this to make testing easier. This way you do not have to type something every time you run the program.

In your outer for loop it looks like you understand that "str.size()" returns an "unsigned int". Your way of type casting the return value is fine, but I wanted to show you the newer version available from C++11 on.

In line 15. You set "key" equal to the first three letters of "str" to check with the if statement. It will stay in this outer for loop until key is equal to "fox". Then it enter the if statement.

The for loop at line 20 will easily step through the "repl" string with no problem, but you need to know where to start in "str".

Looking back at line 15 when the "str.substr()" finds the position that matches "fox" the value of "j" is "16". So in the part str[j + k] adding "16 + 0" leaves you with "16" the starting position of "fox" in the string "str" and for the part repl[k] "k" is zero. So "str[16]" is replaced with "repl[0]". When "k" becomes 1 you would have "str[17]" is replaced with "repl[1]". And next "str[18]" is replaced with "repl[2]".

Since the word "fox" is not found at the beginning of the string you need to know which element of "str" is the starting position of "fox" to have the correct position to use in the second for loop.

The part of the code str[j + k] may seem hard to understand at first. In the end "j + k" just evaluates to a single number, this is done first before str[] is evaluated, then you have str[16] to work with.

Hope that helps,

Andy
Topic archived. No new replies allowed.