Start learning free

LESSON 386 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v2 — Case-Insensitive Match in Scala

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:

def grepCaseInsensitive(lines: Array[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.toLowerCase().contains(lowerPattern). Collect the ORIGINAL line on a hit.

The full solution:
class Solution {
    def grepCaseInsensitive(lines: Array[String], pattern: String): String = {
        val result = scala.collection.mutable.ArrayBuffer[String]()
        val lowerPattern = pattern.toLowerCase()
        for (line <- lines) {
            if (line.toLowerCase().contains(lowerPattern)) {
                result += line
            }
        }
        return result.mkString("\n")
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    Grep V2 in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free