Start learning free

LESSON 13 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep in C#: Filtering Lines with Contains

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 return string.Join("\n", result).

The full solution:
class Solution {
    public string Grep(List<string> lines, string pattern) {
        List<string> result = new List<string>();
        foreach (string line in lines) {
            if (line.Contains(pattern)) {
                result.Add(line);
            }
        }
        return string.Join("\n", result);
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Grep V1 in C#, explained

    Problem overview

    Grep takes a List<string> named lines and a search pattern, and returns every line that contains the pattern, in their original order, joined by newline characters (\n). The search is case-sensitive, and the pattern is plain text: a . or * means itself, not a wildcard as in a regular expression.

    For pattern "err" and lines ["error: foo", "warning", "another error", "ok"], the first and third lines contain err, so the result is "error: foo\nanother error". Printed, that is two lines. If nothing matches, the result is the empty string.

    Approach

    This is a filter: look at each line, keep it if it passes a test, and drop it otherwise. The test is the string method Contains, which is true when the pattern appears anywhere in the line, at the start, in the middle or at the end.

    You do not know how many lines will match, so the kept lines go in a List<string>. A list grows as you add to it, while an array has a fixed length chosen when it is created. At the end the list is turned into one string with a newline between each pair of lines.

    Step by step

    1. Create result, a new empty List<string>. The matches will be collected here.
    2. Loop over lines with foreach, naming each entry line.
    3. Test the line with an if on line.Contains(pattern).
    4. Add the line to result inside the if, with result.Add(line). Only lines that passed the test get there.
    5. Return the joined text with string.Join("\n", result), after the loop.

    The solution in C#

    class Solution {
        public string Grep(List<string> lines, string pattern) {
            List<string> result = new List<string>();
            foreach (string line in lines) {
                if (line.Contains(pattern)) {
                    result.Add(line);
                }
            }
            return string.Join("\n", result);
        }
    }
    

    The details worth knowing:

    • Contains is case-sensitive. "Error".Contains("err") is false. Matching ignoring case is the next lesson.
    • Contains is literal. "a.b".Contains("a.b") is true and "axb".Contains("a.b") is false: the dot is an ordinary character, which is exactly the plain-text behaviour the statement asks for.
    • string.Join(separator, list) puts the separator only between items, never after the last one. A single match gives that line with no newline, and an empty list gives "", so the "no match" case needs no if.
    • "\n" is one character. The escape is a newline, not a backslash followed by an n.
    • The original line is kept. Nothing is changed, so the returned lines are the same strings that came in.

    Complexity

    Let n be the number of lines and m the length of the longest one. Time: each line is searched once, and a search takes at most about the line's length times the pattern's length in the worst case, so the total is at most proportional to n times m times the pattern length. In practice searches for short patterns are fast. Space: the result list holds the matching lines, so it is O(n) references in the worst case, plus the joined string.

    Edge cases and common mistakes

    • No matches. The list stays empty and the method returns "".
    • Every line matches. The result is all the lines, joined by newlines, in the original order.
    • Trailing newline. Building the text with += line + "\n" leaves a newline at the end, which is not what the expected output has. string.Join avoids it.
    • Using == instead of Contains. line == pattern only matches when the whole line equals the pattern.
    • Checking the start only. StartsWith would reject "another error", which the example keeps.

    Testing

    • Pattern "err" with the four lines above gives "error: foo\nanother error".
    • Pattern "ERR" with the same lines gives "".
    • Pattern "a.b" with ["a.b", "axb"] gives "a.b".
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free