Build a tiny version of the Unix cat command. Given a list of lines, return them joined by newline characters (\n) so they print one per line.
Lines can be blank, and the list can be empty (the result is then an empty string).
Function signature:
func cat(lines []string) string
Example:
Input: lines = ["hello", "world", "foo"] Output: "hello\nworld\nfoo" When printed: hello world foo
Build the result manually: walk through the lines in order and accumulate them into a single
string, inserting a "\n" between every pair.
A clean trick: only prepend
"\n" when i > 0. That way the first line has no separator before it, and every subsequent line is preceded by exactly one newline.
result := ""
for i := 0; i < len(lines); i++ {
if i > 0 {
result += "\n"
}
result += lines[i]
}
The full solution:
func cat(lines []string) string {
result := ""
for i := 0; i < len(lines); i++ {
if i > 0 {
result += "\n"
}
result += lines[i]
}
return result
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
