Start learning free

LESSON 13 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep in Kotlin: Lines That Contain a Substring

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:

fun grep(lines: List<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.joinToString("\n").

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

STEP 1 OF 5
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Grep V1 in Kotlin, explained

    Problem overview

    This is the first version of a small grep. The function grep(lines: List<String>, pattern: String): String returns every line that contains pattern as a substring, joined by newline characters. The match is case-sensitive, and if no line matches the result is the empty string.

    With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"] the result is "error: foo\nanother error". Printed, it looks like this:

    error: foo
    another error
    

    The real grep reads the pattern as a regular expression. Here the pattern is plain text, so a character such as . or * means nothing special: "a.c" only matches lines that contain those three characters in a row.

    Approach: filter, then join

    The job has two parts. First you keep the lines that pass a test, and then you glue the survivors into one string. In Kotlin, a MutableList<String> collects the survivors, a for loop visits the lines, and joinToString builds the answer. The order of the output is the order of the input, because lines are added as they are visited.

    Step by step

    1. Create the result list. mutableListOf<String>() makes an empty list that can grow, and it goes in a val named result. A val is fine because the variable is never pointed at another list; only the list's contents change.
    2. Loop over the lines with for (line in lines) and close the brace right away.
    3. Test each line. Inside the loop, an if asks whether line contains pattern, using contains. It is true when the pattern appears anywhere in the line, not only at the start.
    4. Keep the matches. Inside the if, result.add(line) appends the line.
    5. Join and return. After the loop, result.joinToString("\n") glues the kept lines together with a newline between each two.

    The solution in Kotlin

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

    Kotlin details to know:

    • String.contains(other) compares exactly, so "Error" doesn't contain "err". Case-insensitive matching needs an extra step, which comes in the next version.
    • joinToString("\n") puts the separator only between items, never after the last one. The result has no trailing newline, and an empty list joins to the empty string, which is exactly what "no line matched" requires.
    • The parameter lines is a List<String>, a read-only view. That is fine, because the function only reads it. The list that grows is result, a MutableList.
    • One line is returned as it is, so a single match gives that line with no newline at all.

    Edge cases and common mistakes

    • Special characters in the pattern. Because contains(String) is a plain-text search, "a.c" matches the line "a.c" but not "abc", and "a*" only matches a literal star. No escaping is needed.
    • Letter case. With pattern "err", the line "Error" isn't kept, while "error" is.
    • An empty pattern. Every string contains the empty string, so every line is returned.
    • A trailing newline. Appending "\n" to each kept line yourself would leave an extra newline at the end. Let joinToString place the separators.
    • No matches. The loop adds nothing and the result is "", not null and not a message.

    Testing

    These results come from running the reference solution, with each result shown between brackets:

    linespatternresult
    ["a", "b"]"z"[] (empty string)
    ["a.c", "abc", "a*"]"a.c"a.c
    ["a.c", "abc", "a*"]"a*"a*
    ["Error", "error"]"err"error
    ["x", "y"]""both lines, x and y
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free