Problem overview
This lesson builds a tiny version of the Unix grep command. The function grep(_ lines: [String], _ pattern: String) -> String receives an array of lines and a search pattern, and returns every line that contains the pattern as a substring. The comparison is case-sensitive, and the kept lines come back joined into one string with newline characters between them. If no line matches, the result is the empty string.
Take pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"]. The first and third lines contain err, so the result is "error: foo\nanother error". Printed, that is two lines of text. The real grep treats the pattern as a regular expression; here it is always plain text, so characters such as . or * mean nothing special. With the pattern "a.b", the line "a.b" matches and "axb" does not.
Approach
The plan is a filter: look at each line in order, keep the ones that pass the test, and glue the survivors together at the end. Keeping the original order comes for free, because the loop visits the lines in order and appends to the end of an array.
Two standard tools do the heavy lifting. line.contains(pattern) answers whether the pattern appears anywhere inside the line, not only at the start. joined(separator:) turns an array of strings into one string, with the separator placed between each two items and not after the last one. That matters for the output format, since the expected text has no trailing newline.
Step by step
- Create an empty array of strings named
resultwithvar. The matching lines will be collected here, and an array declared withletcouldn't grow. - Loop over the lines with
for line in lines. Each pass,lineis the next element. The closing brace goes in right away, so the steps that follow have a place to go. - Test the line. Inside the loop, start an
ifonline.contains(pattern), which is true when the pattern appears anywhere in the line. - Keep the line. Inside the
if, appendlinetoresult. Only lines that passed the test reach this point. - Join and return. After the loop, return
result.joined(separator: "\n"). When nothing matched,resultis empty and joining nothing gives"", which is the answer the statement asks for.
The solution in Swift
func grep(_ lines: [String], _ pattern: String) -> String {
var result = [String]()
for line in lines {
if line.contains(pattern) {
result.append(line)
}
}
return result.joined(separator: "\n")
}
The details a learner might trip on:
[String]()is an empty array. It is the same asvar result: [String] = []. Swift needs the element type, either from the initializer or from an annotation, because there is nothing in the array to infer it from.containstakes a string here. On an array,containstests for an element. On aString, passing another string tests for a substring, which is what this lesson needs. It compares exactly, so"error".contains("ERR")is false."\n"is one character. The backslash starts an escape sequence for the newline. The returned string holds a real line break, which is why printing it shows each line on its own row.- The method is called on an array.
joined(separator:)is available becauseresultholds strings. The separator is the argument label.
Complexity
With n lines of length up to m and a pattern of length p, the time is at most about O(n * m * p) in the worst case for a naive substring search, and usually much less. Space is O(k) for the k kept lines, plus the joined string.
Edge cases and common mistakes
- No match.
grep(["one"], "zzz")returns"", not a string holding a newline. - Case matters. With the pattern
"err", the line"Error"is not kept, but"error"is. - The pattern can sit anywhere. A line like
"only"matches the pattern"on"at its start, and"another error"matches"err"in its second word. - Special characters are literal.
"a.b"matches the texta.band notaxb, becausecontainsdoes no pattern matching. - Joining by hand. Adding
"\n"after every kept line leaves a trailing newline and the answer is wrong. Letjoined(separator:)place the separators. - An empty pattern. The statement doesn't define it. With Foundation imported,
"abc".contains("")isfalse, so nothing matches.
Testing
| lines | pattern | Result |
|---|---|---|
["error: foo", "warning", "another error", "ok"] | "err" | "error: foo\nanother error" |
["a.b", "axb"] | "a.b" | "a.b" |
["Error", "error"] | "err" | "error" |
["one"] | "zzz" | "" |
[] | "x" | "" |
