Lesson 7 of 10
Strings
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
The find, substr and toupper functions
Explanation
A std::string knows its own length: tag.size() is the number of characters in it, and tag[0] is its first character, whose type is char. + joins two strings into one, and += adds a character or a string to the end. substr(start, count) cuts out part of a string, so if tag is "layan#1024", then tag.substr(0, 5) is "layan". tag.find('#') returns the position where the character first appears, and if it isn't there, it returns a special value called std::string::npos, which is neither -1 nor zero, so compare against it explicitly.
Note that + needs at least one of its two sides to be a std::string. The compiler accepts "HP: " + 2, but it doesn't join anything: it skips the first two characters of the text and prints ": ". So convert the number to a string first: "HP: " + std::to_string(hp).
std::toupper(c) and std::tolower(c) from <cctype> convert a single unaccented letter, A to Z, to upper or lower case, and they return an int, so turn the result back into a character with static_cast<char>. Also keep in mind that std::string stores bytes, not characters, and an accented letter like é takes two bytes in UTF-8, so std::string("José").size() is 5, and [3] is only half of the é. That's why the player names in this lesson's examples use plain unaccented letters: handling text like José one character at a time needs different tools.
Your task
Complete std::string initials(const std::string& full) so it returns the first letter of each word in upper case: initials("layan saad") is "LS", and extra spaces don't count as words. Complete std::string username(const std::string& tag) so it returns whatever comes before the # in a tag like "layan#1024", or the whole string if it has no #. Then complete bool isPalindrome(const std::string& s) so it tells you whether the string reads the same forward and backward, ignoring the difference between upper and lower case: "Racecar" is a palindrome and "hello" isn't.
Checks
6 checks- initials returns the first letter of each word in upper case
- initials works with a single word, extra spaces and an empty string
- username returns whatever comes before #
- username returns the whole string when it has no #
- isPalindrome accepts level and Racecar and rejects hello
- isPalindrome accepts an empty string and a single character and rejects ab