Problem overview
The function stutterize receives a word and returns it as if it were said with a stutter: the first two characters, then a hyphen, then the whole word. The word "dog" becomes "do-dog".
The characters keep their case, so "Hello" becomes "He-Hello", with the capital H in both places. A two-letter word such as "ab" gives "ab-ab": its first two characters are the whole word.
Approach
The result has three parts, always in the same order. The first part is a piece of the word, the second is a fixed hyphen, and the third is the word itself. The task is to produce the parts and join them.
The word has at least two letters, so its first two characters always exist. That means no length check is needed.
Step by step
- Take the first two characters.
word.substr(0, 2)starts at index 0 and takes 2 characters. The second number is how many characters to take, not the index where the piece stops. - Add the hyphen. The hyphen is the literal
"-", in double quotes, because a string literal can be joined to astd::stringwith+. - Add the whole word at the end, and return the joined string.
The solution in C++
class Solution {
public:
string stutterize(string word) {
return word.substr(0, 2) + "-" + word;
}
};
Some C++ details about this line:
- Evaluation order. The
+operators are evaluated from left to right. Firstword.substr(0, 2) + "-"joins astd::stringand a literal into a new string, and then that string is joined withword. Because the leftmost operand is already astd::string, every step is a string join. - Why the order matters. If the expression began with two literals, such as
"-" + "x" + word, it wouldn't compile: C++ has no+for two string literals. Here the first operand is the result ofsubstr, so that problem doesn't come up. - Double quotes versus single quotes.
"-"is a string and'-'is a singlechar. Joining astd::stringand acharwith+also works and appends that character, but the lesson uses a string literal. substrmay take fewer characters than asked. If the string is shorter thanpos + count,substrjust stops at the end of the string. For"ab",substr(0, 2)is the whole word.
Edge cases and common mistakes
- Reading the second argument as an end position.
substr(0, 2)gives two characters, at indexes 0 and 1. It doesn't stop at index 2 and it doesn't include it. - Using only the stutter. The result ends with the whole word, not with the remaining letters. For
"dog"it is"do-dog", not"do-g". - Forgetting the hyphen. Without it,
"dog"would give"dodog". - Changing the case. The first two characters are copied as they are.
"Hello"starts with an upper-case H, so the stutter starts with one too. - A word of two letters. This is the shortest legal input, and
"ab"gives"ab-ab". The same code covers it with no special case.
Testing
"dog"gives"do-dog"."Hello"gives"He-Hello"."ab"gives"ab-ab".
