Start learning free

LESSON 14 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep -i in Kotlin: Case-Insensitive Substring Match

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:

fun grepCaseInsensitive(lines: List<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.lowercase().contains(lowerPattern). Add the ORIGINAL line on a hit.

The full solution:
class Solution {
    fun grepCaseInsensitive(lines: List<String>, pattern: String): String {
        val result = mutableListOf<String>()
        val lowerPattern = pattern.lowercase()
        for (line in lines) {
            if (line.lowercase().contains(lowerPattern)) {
                result.add(line)
            }
        }
        return result.joinToString("\n")
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Grep V2 in Kotlin, explained

    Problem overview

    This version adds the -i flag to the small grep. The function grepCaseInsensitive(lines: List<String>, pattern: String): String returns every line that contains pattern as a substring while ignoring letter case, joined by newline characters. The lines that come back keep their original capitalization, and when nothing matches the result is the empty string. The lines contain only ASCII characters.

    With pattern = "ERR" and lines = ["Error: 1", "ok"], the result is "Error: 1". The pattern is in capitals and the line isn't, yet it matches, and the line is returned exactly as it was written.

    Approach: compare in one case, return the original

    A plain contains is case-sensitive, so "Error: 1".contains("ERR") is false. The fix is to bring both sides to the same case before comparing. If the pattern and the line are both lowercase, then ERR becomes err and finds the start of error: 1.

    The important detail is what you store. The lowercase copy of the line exists only for the test. The list of results receives the original line, so capitals survive. If you added the lowercase copy instead, "Error: 1" would come back as "error: 1" and the lesson's tests would fail.

    The pattern is the same for every line, so it is lowercased once before the loop. Each line has to be lowercased inside the loop, because each one is different.

    Step by step

    1. Create the result list. mutableListOf<String>() goes in a val named result. The variable never changes, only the list's contents do.
    2. Lowercase the pattern once. pattern.lowercase() goes in a val named lowerPattern, placed outside the loop so it isn't recomputed for every line.
    3. Loop over the lines with for (line in lines), closing the brace immediately.
    4. Compare in lowercase. The if checks whether line.lowercase() contains lowerPattern. Both sides are lowercase now, so ERR finds Error, while line itself is untouched.
    5. Keep the original line. Inside the if, result.add(line) stores the line with its capitals.
    6. Join and return. result.joinToString("\n") puts a newline between the kept lines, and gives the empty string when the list is empty.

    The solution in Kotlin

    class Solution {
        fun grepCaseInsensitive(lines: List<String>, pattern: String): String {
            val result = mutableListOf<String>()
            val lowerPattern = pattern.lowercase()
            for (line in lines) {
                if (line.lowercase().contains(lowerPattern)) {
                    result.add(line)
                }
            }
            return result.joinToString("\n")
        }
    }
    

    Kotlin details to know:

    • lowercase() returns a new string. Strings are immutable in Kotlin, so calling line.lowercase() never changes line. That is why the original is still available to add to result.
    • Older Kotlin code uses toLowerCase(). lowercase() replaced it as the current name.
    • The standard library has a built-in shortcut: line.contains(pattern, ignoreCase = true) is true for "Error: 1" and "ERR". The lesson spells the idea out with lowercase() so that you see what ignoring case means.
    • Writing val for lowerPattern documents that it is computed once and never reassigned.

    Edge cases and common mistakes

    • Returning the lowercase line. The output must keep the original casing: ["Error: 1", "ok"] with "ERR" gives Error: 1, not error: 1.
    • Lowercasing only one side. Writing line.contains(lowerPattern) would miss "Error" if only the pattern were lowercased, because the line's capital E wouldn't match e. Both sides must be in the same case.
    • Letters in the middle of a word. The match is a substring match, so "err" also finds "tERRor".
    • No matches. An empty result list joins to "".
    • Non-ASCII text. Case rules for other alphabets are more complicated, and this lesson's input avoids them.

    Testing

    These results come from running the reference solution:

    linespatternresult
    ["Error: 1", "ok"]"ERR"Error: 1
    ["Error: 1", "ok", "tERRor"]"err"Error: 1 and tERRor, on two lines
    ["a"]"b"the empty string
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free