String Algorithms in C++
Level 5329 keystrokes
Uses find to locate both occurrences of "Hello" (positions 0 and 14), then replace to change "World" into "C++" in a copy of the string.
C++ code
1string text = "Hello, World! Hello, Universe!";2 // find returns the index of the first match3size_t pos = text.find("Hello");// Prints 04cout << "First Hello at: " << pos << endl;5 // Searches again starting just after the first match6pos = text.find("Hello", pos + 1);// Prints 14 (find would return string::npos if nothing were found)7cout << "Second Hello at: " << pos << endl;8 // Copies the string so the original text stays unchanged9string replaced = text;// Position of "World"10size_t start = replaced.find("World");// Replaces 5 characters from start ("World") with "C++"11replaced.replace(start, 5, "C++");// Prints "Hello, C++! Hello, Universe!"12cout << replaced << endl;Output
First Hello at: 0 Second Hello at: 14 Hello, C++! Hello, Universe!
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C++ code and how often they appear.
<× 16"× 14;× 9,× 5=× 5.× 4(× 4)× 4+× 3_× 2