Start learning free

LESSON 14 OF 71 · PROJECTS: COMMAND-LINE TOOLS

grep -i in Swift: Case-Insensitive Match with lowercased

Practice Read the full explanation

Build the -i flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring, ignoring letter case. Return the matching lines joined by newline characters (\n).

Function signature:

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

Example:

Input:
pattern = "ERR"
lines = ["Error: 1", "ok"]

Output: "Error: 1"

When printed:
Error: 1

The matching is case-insensitive but the original line (preserving its original casing) is returned. If no lines match, return the empty string "". The lines contain only ASCII characters.


Lowercase the pattern once, then for each line check line.lowercased().contains(lowerPattern). Append the ORIGINAL line on a hit.

The full solution:
class Solution {
    func grepCaseInsensitive(_ lines: [String], _ pattern: String) -> String {
        var result = [String]()
        let lowerPattern = pattern.lowercased()
        for line in lines {
            if line.lowercased().contains(lowerPattern) {
                result.append(line)
            }
        }
        return result.joined(separator: "\n")
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Grep V2 in Swift, explained

    Problem overview

    The second version of the grep project adds the -i flag. The function grepCaseInsensitive(_ lines: [String], _ pattern: String) -> String returns every line that contains the pattern as a substring, ignoring letter case, joined by newline characters. The lines that come back keep their original casing, and if nothing matches the result is the empty string. The lines contain only ASCII characters.

    With pattern = "ERR" and lines = ["Error: 1", "ok"], the first line matches even though its letters are Err and not ERR, and the result is "Error: 1". The second line has no err in any casing.

    Approach

    Version 1 compared the line and the pattern exactly. To ignore case, make both sides the same case before comparing. Converting to lowercase is the usual choice: "Error" becomes "error", "ERR" becomes "err", and the plain contains check then finds the match.

    The conversion is only for the test. What goes into the result is the original line, so a matching "Error: 1" is returned as written and not as "error: 1".

    The pattern is the same for every line, so it needs lowercasing just once, before the loop. Doing it inside the loop would give the same answers but repeat the work for every line. The lines differ from one another, so each one is lowercased on its own turn.

    Step by step

    1. Create an empty array of strings named result with var, to collect the matching lines.
    2. Lowercase the pattern once into a let named lowerPattern, using pattern.lowercased(). It never changes, so let fits.
    3. Loop over the lines with for line in lines, writing the closing brace right away.
    4. Test a lowercase copy of the line. Start an if on line.lowercased().contains(lowerPattern). Both sides are lowercase, so ERR finds Error. The line itself isn't changed.
    5. Append the original line to result, capitals and all.
    6. Join and return with result.joined(separator: "\n"). An empty result gives the empty string.

    The solution in Swift

        func grepCaseInsensitive(_ lines: [String], _ pattern: String) -> String {
            var result = [String]()
            let lowerPattern = pattern.lowercased()
            for line in lines {
                if line.lowercased().contains(lowerPattern) {
                    result.append(line)
                }
            }
            return result.joined(separator: "\n")
        }
    

    The details a learner might trip on:

    • lowercased() returns a new string. Strings are values in Swift, so the call doesn't modify line or pattern. That is why appending line afterwards still gives the original text.
    • Method, not property. It is lowercased() with parentheses and a trailing d. The shorter-looking lowercase doesn't exist on String.
    • Appending the wrong thing. result.append(line.lowercased()) would compile and run, but the output would lose the original casing, and the lesson's tests would fail on lines like "Error: 1".
    • ASCII only. Case conversion is simple for ASCII letters. For other alphabets the rules are more complicated, and this lesson avoids them by keeping the input to ASCII.

    Complexity

    Each line is lowercased once, which costs time proportional to its length, and then searched. The total time is proportional to the number of characters in all lines, times the pattern length in the worst case for the substring search. Extra space is the lowercase copy of one line at a time, plus the array of kept lines and the joined result.

    Edge cases and common mistakes

    • Casing in the output. ["Error", "eRROR", "fine"] with the pattern "error" returns "Error\neRROR", each line exactly as it came in.
    • Lowercasing only one side. If the line is lowercased but not the pattern, "ERR" never matches anything.
    • No match returns "", as does an empty array of lines.
    • An empty pattern is not defined by the statement. With Foundation imported, contains("") is false in Swift, so nothing is returned.
    • A trailing newline. Build the output with joined(separator:) and not by appending "\n" to each line.

    Testing

    linespatternResult
    ["Error: 1", "ok"]"ERR""Error: 1"
    ["Error", "eRROR", "fine"]"error""Error\neRROR"
    ["ok"]"ERR"""
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free