Start learning free

LESSON 619 OF 678 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v2 — Case-Insensitive Match

Practice

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