Changing a String
substr() returns a new string and leaves the original as it is. Three other methods change the string itself:
text.insert(index, part)insertspartbefore the character atindex.text.erase(index, count)removescountcharacters, starting atindex. Withoutcount, it removes everything fromindexto the end.text.replace(index, count, part)removescountcharacters, starting atindex, and putspartin their place. The new part can be longer or shorter than the old one.
std::string name = "Aria";
name.insert(0, "[DK] ");
std::cout << name << std::endl;
name.erase(0, 5);
std::cout << name << std::endl;
std::string message = "gg!!!!!!";
message.erase(3);
std::cout << message << std::endl;
std::string command = "go north";
command.replace(3, 5, "south");
std::cout << command << std::endl;This prints:
[DK] Aria
Aria
gg!
go southThe index usually comes from find(). This is how a chat filter hides a rude word:
std::string message = "you are a noob";
int position = message.find("noob");
if (position != std::string::npos) {
message.replace(position, 4, "****");
}
std::cout << message << std::endl;This prints:
you are a ****The check matters. When the word isn't in the message and you pass npos to replace(), the program stops with std::out_of_range: basic_string, just as substr() does with a start past the end.
Instructions
- 1
In place of the first comment, write a function
censorwith two parameters: the messagemessage, which the function changes, and the wordword, which it only reads. Choose how to pass them, as you learned in the lesson on references. The function finds the word in the message and replaces it with as many asterisks as the word has characters;std::string(count, character)makes them. When the word isn't in the message, the function changes nothing. In place of the second comment, call it for each of the three messages withbadWord. The first line of the output is thenyou are such a ****, and the third staysgg, well played. The test also runs your program with another bad word. - 2
The second message still has one
noobin it, becausefind()finds only the first one. Change the function so that it replaces every occurrence of the word: search again in a loop untilfind()finds nothing. The second line is then**** team, **** moves.