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