Problem overview
The function concatFirstAndLastChar receives a string s of at least two characters and returns a new two-character string: the first character of s followed by its last one.
For "hello" the result is "ho". For "Hello World!" it is "H!": every character counts, so the last one is the exclamation mark, and the capital H stays as it is. For "ab" the first and last characters are the whole string, so the result is "ab".
Approach
There is nothing to loop over. A string in Go is a sequence of bytes numbered from 0, so the first character sits at index 0 and the last one at index len(s)-1. The task is to read those two positions and join them into one string.
The only wrinkle is the type you get back. Indexing a string with s[i] gives a byte (an alias of uint8), which is a number, not a string. The + operator joins strings, so each byte must be turned into a one-character string first. That is what the conversion string(...) does.
For "hello" the length is 5, so the last index is 4. The bytes at indexes 0 and 4 are h and o, and joined they give "ho". The same two expressions work for a string of any length, from 2 characters up, because they depend only on len(s).
Step by step
- Read the first byte with
s[0]. - Read the last byte with
s[len(s)-1]. The length is the number of bytes, and counting starts at 0, so the last valid index is one less than the length. - Wrap each byte in
string(...)so that it becomes a one-character string. - Join them with
+and return the result.
The solution in Go
func concatFirstAndLastChar(s string) string {
return string(s[0]) + string(s[len(s)-1])
}
Running it on the three examples gives these results:
"hello" -> "ho"
"Hello World!" -> "H!"
"ab" -> "ab"
Two details are worth knowing:
s[0]is a byte, not a string. Withoutstring(...)the+would add two numbers instead of joining two strings, and the function would not compile because it must return astring.- Indexing works on bytes. For English letters, digits, spaces and punctuation, one character is one byte, so this solution is exact. A character such as
étakes two bytes in UTF-8, sos[0]would be only half of it. Withs = "éa", this function returns"Ãa", because the single byte 195 becomes the characterÃ. Handling such text means converting to a[]runefirst, which this lesson doesn't need.
Edge cases and common mistakes
- Using
len(s)as the last index. Indexes run from 0 tolen(s)-1, sos[len(s)]stops the program with an "index out of range" panic. - Leaving out
string(...). The compiler rejects the code, because a number cannot be returned where a string is expected. - Two-character input. With
"ab"the first and last indexes are 0 and 1, which is fine. The constraint of at least 2 characters is what keeps the two positions valid and different. - Changing the case. The characters are copied as they are; nothing here needs
strings.ToUpperorstrings.ToLower.
Testing
"hello"gives"ho"."Hello World!"gives"H!"."ab"gives"ab".
