Problem overview
The function stutterize receives a word and returns it said with a stutter: its first two characters, a hyphen, then the whole word.
For "dog" the answer is "do-dog". For "Hello" it is "He-Hello", with the capital letter kept. For the two-letter word "ab" the first two characters are the whole word, so the answer is "ab-ab".
Approach
The result has three parts: a slice of the word, a fixed hyphen, and the word itself. word.substring(0, 2) gives the first two characters, and + joins the three parts into one string.
Step by step
- Cut the first two characters with
word.substring(0, 2). The end index is exclusive, so this keeps indexes 0 and 1. - Add the hyphen as the string
"-". - Add the whole
wordand return the result.
The solution in Kotlin
class Solution {
fun stutterize(word: String): String {
return word.substring(0, 2) + "-" + word
}
}
Details worth knowing:
- Everything is a
String.substringreturns a string,"-"is a string, andwordis a string, so every+is plain string concatenation. - Double quotes for strings.
"-"is a one-characterString.'-'would be aChar;String + Charalso works in Kotlin, but the string form keeps the three parts the same type. - A template works too.
"${word.substring(0, 2)}-$word"builds the same text. - The original is not modified. Strings are immutable, so
wordis unchanged after the call.
Tracing the examples
For "dog", word.substring(0, 2) is "do". Adding "-" gives "do-", and adding the whole word gives "do-dog".
For "Hello", the slice is "He" and the result is "He-Hello".
For "ab", the slice is "ab" and the result is "ab-ab". The stutter and the word are the same text here.
The + operators are evaluated from left to right, so the slice and the hyphen are joined first and the word comes last. Because every part is a String, the order of the pieces in the code is the order of the pieces in the result.
Why a slice and not a character
It is tempting to build the stutter from single characters, such as word[0] and word[1]. That fails because indexing returns a Char, and Char values can't be joined with + the way strings can. A slice keeps the pieces as strings, so there's nothing to convert.
The same slice also explains the name of the exercise. A stutter repeats the start of a word, and substring(0, 2) is exactly "the start of the word, two characters long". Change the 2 to another number and the function stutters with a longer or shorter beginning, as long as the word has that many characters.
Edge cases and common mistakes
- Two-letter words.
substring(0, 2)on"ab"returns"ab", so the result is"ab-ab". - Using end index 1.
substring(0, 1)keeps only the first character and gives"d-dog". - Changing case. Nothing is converted:
"Hello"gives"He-Hello", not"he-Hello". - Words shorter than two characters. The lesson rules them out. A one-letter word would make
substring(0, 2)throw aStringIndexOutOfBoundsException.
Testing
"dog"gives"do-dog"."Hello"gives"He-Hello"."ab"gives"ab-ab".
