Start learning free

LESSON 13 OF 71 · PROJECTS: COMMAND-LINE TOOLS

grep in Swift: Filtering Lines with contains and joined

Practice Read the full explanation

Build a tiny version of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring (case-sensitive), joined by newline characters (\n).

Function signature:

func grep(_ lines: [String], _ pattern: String) -> String

Example:

Input:
pattern = "err"
lines = ["error: foo", "warning", "another error", "ok"]

Output: "error: foo\nanother error"

When printed:
error: foo
another error

If no lines match, return the empty string "".

Note: real grep treats the pattern as a regular expression by default (grep -F matches plain text). Here the pattern is always plain text: just look for it literally, so characters such as . or * mean nothing special.


Iterate over the lines, keep the ones where line.contains(pattern) is true, then return result.joined(separator: "\n").

The full solution:
class Solution {
    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")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Grep V1 in Swift, explained

    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

    1. Create an empty array of strings named result with var. The matching lines will be collected here, and an array declared with let couldn't grow.
    2. Loop over the lines with for line in lines. Each pass, line is the next element. The closing brace goes in right away, so the steps that follow have a place to go.
    3. Test the line. Inside the loop, start an if on line.contains(pattern), which is true when the pattern appears anywhere in the line.
    4. Keep the line. Inside the if, append line to result. Only lines that passed the test reach this point.
    5. Join and return. After the loop, return result.joined(separator: "\n"). When nothing matched, result is 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 as var 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.
    • contains takes a string here. On an array, contains tests for an element. On a String, 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 because result holds 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 text a.b and not axb, because contains does no pattern matching.
    • Joining by hand. Adding "\n" after every kept line leaves a trailing newline and the answer is wrong. Let joined(separator:) place the separators.
    • An empty pattern. The statement doesn't define it. With Foundation imported, "abc".contains("") is false, so nothing matches.

    Testing

    linespatternResult
    ["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"""
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free