Part of a String
Often you need only a part of a string: the first name from a full name, or the time from a line of a chat. The method substr() (short for substring, a part of a string) returns one. It takes two numbers: the index where the part starts, and the number of characters, its length:
std::string weapon = "Iron Sword";
std::cout << weapon.substr(0, 4) << std::endl;
std::cout << weapon.substr(5, 3) << std::endl;
std::cout << weapon.substr(5) << std::endl;
std::cout << weapon << std::endl;This prints:
Iron
Swo
Sword
Iron SwordThe second number is the length of the part, not the index where it ends. weapon.substr(5, 3) takes three characters starting at index 5, the ones at the indexes 5, 6 and 7. Without the second number, the part goes all the way to the end. And as the last line shows, substr() doesn't change the original string: it returns a new one, which you can print or store in a variable.
What if the numbers don't fit the string? "Iron Sword" has 10 characters, at the indexes 0 to 9:
- When the part would reach past the end, you get the characters there are:
weapon.substr(5, 100)is"Sword". - A start right at the end,
weapon.substr(10), gives an empty string,"". - A start past the end stops the program:
std::string weapon = "Iron Sword";
std::cout << weapon.substr(20) << std::endl;
std::cout << "End" << std::endl;The program never prints End. Its output ends with an error instead:
std::out_of_range: basic_string
RuntimeError: unreachableIt's the same out_of_range error that at() gives for an index outside a vector. basic_string is the name the library uses for std::string inside.
Instructions
- 1
Each line of the game's chat starts with the time in square brackets. The time starts at index 1 and has 5 characters. Below the print line, store it in a variable
timewithsubstr(), and print it:Time: 18:05. The test also runs your program with another chat line. - 2
The message starts at index 8, after the closing bracket and the space, and goes to the end of the line. Store it in a variable
messagewithsubstr()and only one number, and print it:Message: Who wants to fight the dragon?.