Problem overview
The function grep(lines []string, pattern string) string is a tiny version of the Unix grep command. It returns every line that contains pattern as a substring, joined with newline characters (\n). The match is case-sensitive, and the lines keep their original order.
With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"], two lines contain err, so the result is "error: foo\nanother error". When nothing matches, the result is the empty string.
Real grep reads the pattern as a regular expression. Here it is plain text: . and * mean nothing special, and a pattern like "a.b" only matches those three characters in a row.
Approach
This is a filter. Walk through the lines, keep the ones that pass a test, and glue the survivors together. The test is a single standard-library call, strings.Contains(line, pattern), which reports whether the first string holds the second anywhere inside it, not only at the start.
The kept lines go into a slice, and one call to strings.Join turns the slice into the final string. Building the answer by adding "\n" after every line would leave a trailing newline, or an extra one at the front, and would need care at the edges. Join puts the separator only between two items, so a single match gives the line alone, and no match gives "".
Step by step
- Declare the function with the slice of lines and the pattern as parameters, and a
stringresult. - Create an empty slice named
resultwith[]string{}. It starts empty because nothing has matched yet. - Loop with
range.for _, line := range linesgives each element aslineand discards the index with_. - Test the line.
if strings.Contains(line, pattern)is true when the pattern appears somewhere in the line. - Keep the line.
result = append(result, line)adds it.appendreturns the grown slice, so the result must be stored back inresult. - Join and return.
strings.Join(result, "\n")builds the output.
The solution in Go
func grep(lines []string, pattern string) string {
result := []string{}
for _, line := range lines {
if strings.Contains(line, pattern) {
result = append(result, line)
}
}
return strings.Join(result, "\n")
}
Go details worth knowing:
appendmay allocate a new array. A slice is a small header that points to an array. When the array is full,appendcopies the elements into a bigger one and returns a header for it, so callingappend(result, line)and ignoring the return value would lose the line.[]string{}is empty but notnil.var result []stringwould also work here:appendandstrings.Joinaccept anilslice, and joining either one gives"".- The pattern is literal.
strings.Containsdoes no regular-expression work, sogrep(["a.b", "axb", "a*"], "a.b")returns just"a.b", and the pattern"a*"returns just"a*". - The returned lines are unchanged. The function doesn't trim or modify them, and lines that are themselves empty are kept when they match.
Complexity
Time: O(n * m) in the worst case, where n is the total length of the lines and m the pattern length, since a substring search may compare the pattern at many positions. In practice strings.Contains is much faster than that bound suggests. Space: O(k), where k is the size of the output: the result slice holds the matching lines (as references to the originals), and Join builds one new string of their combined length.
Edge cases and common mistakes
- No match.
grep(["error: foo", "warning", "another error", "ok"], "xyz")returns"". - Case matters. The pattern
"Err"doesn't match"error: foo", so that call also returns"". Ignoring case is the next version's job. - Empty pattern. Every string contains the empty string, so
grep(["x", "y"], "")returns"x\ny". - Empty list of lines. The loop doesn't run and the result is
"". - Special characters. Treating the pattern as a regular expression would make
"a.b"match"axb".strings.Containsavoids that. - Dropping the stored result of
append. The compiler rejects a bareappend(result, line)statement with an error that its result is not used.
Testing
["error: foo", "warning", "another error", "ok"]with"err"gives"error: foo\nanother error".- The same lines with
"Err"give"". ["a.b", "axb", "a*"]with"a.b"gives"a.b".["x", "y"]with""gives"x\ny".[]with"x"gives"".
