Problem overview
The function amazingToNotAmazing receives a word s that starts with a lower-case a and returns "not " followed by the word without its first character. The word "amazing" becomes "not mazing".
Only the first character is removed. For "aMAZING" the result is "not MAZING", with the upper-case letters untouched. For "an" it is "not n": removing the a leaves a single letter. The space is part of the prefix "not ", so it appears exactly once, between not and the rest of the word.
Approach
The job has two parts: get "everything except the first character", then put a fixed prefix in front. Go has a direct tool for the first part, the slice expression s[low:high]. It returns the part of the string from index low up to, but not including, index high. Either bound can be left out: a missing low means 0, and a missing high means the end of the string.
So s[1:] starts at index 1 and runs to the end. That is the word without its first character. No loop and no helper function is needed, and nothing depends on the length of the word.
Step by step
- Slice from index 1 with
s[1:], leaving out the end index so that the slice reaches the last character. - Write the prefix as the string literal
"not ", with its trailing space inside the quotes. - Join them with
+and return the result in a singlereturnstatement.
The solution in Go
func amazingToNotAmazing(s string) string {
return "not " + s[1:]
}
Calling it on the three examples gives these results:
"amazing" -> "not mazing"
"aMAZING" -> "not MAZING"
"an" -> "not n"
A few details about Go's strings and slices:
- A slice of a string is a string. Unlike slicing a
[]int, slicing a string gives anotherstring, so it can be joined with+directly. No conversion is needed. - Strings are immutable. You can't delete the first character in place;
s[1:]produces a new string value and leavessas it was. - The end index is excluded. That is why
s[0:2]holds two characters, and why leaving the end out is the easy way to say "to the end". - Indexes count bytes. For English letters, one letter is one byte, so removing one byte removes one letter. A character outside plain English text, such as
é, takes two bytes, ands[1:]would cut it in half. The constraints for this lesson keep the words to English letters.
Edge cases and common mistakes
- Forgetting the space.
"not" + s[1:]gives"notmazing". The space must be inside the quotes of the prefix. - Starting the slice at 0.
s[0:]is the whole word, so nothing is removed and"amazing"becomes"not amazing". - Starting the slice at 2. This drops two characters, giving
"not azing". - An empty string. The constraints promise at least 2 characters, so
s[1:]is always valid. On an empty string,s[1:]would stop the program with a "slice bounds out of range" panic. - Changing the case. The rest of the word is copied exactly as it is, so there is no reason to call
strings.ToLower.
Testing
"amazing"gives"not mazing"."aMAZING"gives"not MAZING"."an"gives"not n".
