Start learning free

LESSON 13 OF 68 · PROJECTS: COMMAND-LINE TOOLS

grep in Java: Substring Match with contains and String.join

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:

public String grep(List<String> lines, String pattern)

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 String.join("\n", result).

The full solution:
class Solution {
    public String grep(List<String> lines, String pattern) {
        List<String> result = new ArrayList<>();
        for (String line : lines) {
            if (line.contains(pattern)) {
                result.add(line);
            }
        }
        return String.join("\n", result);
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Grep V1 in Java, explained

    Problem overview

    The method grep takes a List<String> named lines and a search string pattern. It returns every line that contains the pattern as a substring, in their original order, joined into one string with newline characters between them. The match is case-sensitive. If no line matches, the result is the empty string "".

    For pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"] the result is "error: foo\nanother error". Printed, that is two lines:

    error: foo
    another error
    

    Real grep treats the pattern as a regular expression. Here the pattern is plain text, so characters such as . and * mean nothing special.

    Approach: filter, then join

    The task has two separate parts. First, filter: go through the lines and keep those where line.contains(pattern) is true. Second, format: glue the kept lines into a single string. Collecting the survivors in a list first keeps the two parts apart, and the second part becomes one library call.

    A list is the natural container for the survivors because the number of matches is unknown in advance. An array needs its size fixed up front, while an ArrayList grows with each add.

    Step by step

    1. Create result, a List<String> set to new ArrayList<>(). The diamond <> lets the compiler infer the element type from the variable's declared type.
    2. Loop over the lines with a for-each loop. It hands over each String line directly, so there is no index to manage.
    3. Test each line with if (line.contains(pattern)). contains is true when the pattern appears anywhere in the line, at the start, in the middle or at the end, not only at the beginning.
    4. Keep the match with result.add(line). Only lines that passed the test reach this statement, and the lines keep their original order because the loop visits them in order.
    5. Join and return with String.join("\n", result). The first argument goes between every two elements, and nothing is added before the first or after the last. When result is empty, joining nothing gives "", which is exactly what the task asks for when no line matches, so no special case is needed.

    The solution in Java

    class Solution {
        public String grep(List<String> lines, String pattern) {
            List<String> result = new ArrayList<>();
            for (String line : lines) {
                if (line.contains(pattern)) {
                    result.add(line);
                }
            }
            return String.join("\n", result);
        }
    }
    

    The Java details worth a closer look:

    • contains is a literal search. String.contains takes a CharSequence and compares characters exactly as given. With pattern = "a.b" and the lines ["a.b", "axb"], only "a.b" is returned: the dot is an ordinary character. Methods such as matches or split work differently, because they read their argument as a regular expression.
    • Case matters. contains distinguishes E from e. For ["Error", "error"] and the pattern "error" the result is just "error".
    • String.join accepts a list. Besides varargs strings, it takes any Iterable of CharSequence, so result goes in as it is.
    • Imports. List and ArrayList live in java.util; a standalone file needs import java.util.*;.
    • The newline. "\n" is a single newline character. There is no trailing newline after the last line, because join only places the separator between elements.

    Complexity

    Let n be the number of lines and m the total number of characters in them.

    Time: O(m * p) in the worst case, where p is the pattern length. Each contains call scans one line, and a naive search may compare up to p characters at each position. For short patterns this is close to O(m). Joining the result copies at most every character once more.

    Space: O(n + m). The list holds up to n references to existing strings, and the joined result is a new string of up to about m characters.

    Edge cases and common mistakes

    • No match. ["a", "b"] with "z" gives "". The same happens for an empty list of lines.
    • An empty pattern. Every string contains "", so every line is kept: ["one", "two"] with "" gives "one\ntwo".
    • A single match. The result has no newline in it: ["only"] with "on" gives "only".
    • Ambiguous empty results. A list holding one empty line, with an empty pattern, also joins to "". The result string alone cannot tell "no lines" from "one empty line".
    • Using == or startsWith. line == pattern compares references, and startsWith only checks the beginning. Neither does what the task describes.
    • Adding a newline to each line and returning the concatenation. That leaves a trailing newline that the expected result does not have.

    Testing

    • ["error: foo", "warning", "another error", "ok"] with "err" gives "error: foo\nanother error".
    • ["a", "b"] with "z" gives "".
    • ["a.b", "axb"] with "a.b" gives "a.b".
    • ["Error", "error"] with "error" gives "error".
    • ["one", "two"] with "" gives "one\ntwo".
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free