Problem overview
The function stutterize receives a word and returns it said with a stutter: its 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". A two-letter word stutters on itself: "ab" becomes "ab-ab", because its first two characters are the whole word.
Approach
The result is three pieces in a row, and only the first one needs any work:
- the first two characters of
word; - the hyphen, a fixed string
"-"; - the whole word, unchanged.
For the first piece, Go's slice expression word[0:2] returns the characters from index 0 up to, but not including, index 2: the characters at indexes 0 and 1. The result of a string slice is a string, so all three pieces can be joined with +.
Step by step
- Cut the stutter with
word[0:2]. The end index is excluded, so this holds exactly two characters. - Add the hyphen as the literal
"-". - Add the whole word, just
word. - Return the three pieces joined with
+.
The solution in Go
func stutterize(word string) string {
return word[0:2] + "-" + word
}
Running it on the three examples gives these results:
"dog" -> "do-dog"
"Hello" -> "He-Hello"
"ab" -> "ab-ab"
Some details worth knowing:
- Slicing a string gives a string. In Go, indexing a string (
word[0]) gives a singlebyte, but a slice (word[0:2]) gives astring. That is why nostring(...)conversion is needed here. - The upper bound is exclusive.
word[0:2]is two characters;word[0:1]would be one. The bound may equal the length of the string, which is why a two-letter word works. +builds a new string. Go strings can't be changed in place, so the expression creates a fresh string and leaveswordas it was.- Slices count bytes. For English letters, a byte is a character, which is what the constraints promise. A character such as
étakes two bytes, soword[0:2]could split it.
Edge cases and common mistakes
- A two-letter word.
word[0:2]is the full word, so the result is the word twice with a hyphen between, as in"ab-ab". - A word shorter than 2 letters. The constraints rule it out. In Go, a slice whose end is beyond the string's length stops the program with a "slice bounds out of range" panic. For example, slicing
"a"up to index 2 fails with "slice bounds out of range [:2] with length 1". - Taking three characters.
word[0:3]would turn"dog"into"dog-dog", which is not a stutter. - Using single quotes for the hyphen.
'-'is a rune, a number, not a string, so it can't be joined to strings with+. Use the double-quoted"-". - Changing the case. The stutter starts with a capital
Hfor"Hello"because the word does. Don't call a case function.
Testing
"dog"gives"do-dog"."Hello"gives"He-Hello"."ab"gives"ab-ab".
