Start learning free

LESSON 14 OF 69 · PROJECTS: COMMAND-LINE TOOLS

grep -i in C#: Case-Insensitive Search

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:

public string GrepCaseInsensitive(List<string> lines, string pattern)

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.ToLower().Contains(lowerPattern). Add the ORIGINAL line on a hit.

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

STEP 1 OF 6
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Grep V2 in C#, explained

    Problem overview

    GrepCaseInsensitive takes a List<string> named lines and a pattern. It returns the lines that contain the pattern, ignoring letter case, joined by \n. The lines that come back keep their original capitalisation, and a result with no matches is the empty string.

    For pattern "ERR" and lines ["Error: 1", "ok"], the first line matches because Err is ERR apart from case. The result is "Error: 1", with its capital E untouched. The lines contain only ASCII characters.

    Approach

    The plain version of this search is case-sensitive, so "Error".Contains("ERR") is false. To ignore case, compare both sides in the same case: convert the pattern to lowercase, and convert each line to lowercase for the test only. A line matches when its lowercase copy contains the lowercase pattern.

    The conversion creates a new string each time, and strings in C# are immutable, so the original line is never changed. That is what allows the method to test with the lowercase copy and still add the original line to the result.

    Step by step

    1. Create result, an empty List<string> for the matches.
    2. Lowercase the pattern once, into lowerPattern. It does not change between lines, so doing it before the loop avoids repeating the work.
    3. Loop over lines with foreach.
    4. Test the lowercase line. Inside the loop, ask whether line.ToLower() contains lowerPattern.
    5. Add the original line, not the lowercase copy, to result.
    6. Return the joined text with string.Join("\n", result).

    The solution in C#

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

    The details worth knowing:

    • ToLower() returns a new string. Calling pattern.ToLower(); on its own line and ignoring the result does nothing, because the original is immutable. The result has to be stored or used.
    • Keep the original for the result. Adding line.ToLower() instead of line would return "error: 1" for the example, which is wrong.
    • Why ASCII matters here. For ASCII letters, lowercasing both sides is a sound way to ignore case. Other alphabets have trickier rules, for example "Straße".ToLower() is "straße", so a comparison by lowercase would not treat it like "STRASSE". The lesson avoids that by limiting the input.
    • Another way to write it. line.Contains(pattern, StringComparison.OrdinalIgnoreCase) asks the same question without building a lowercase copy of each line. The lesson uses ToLower because it shows the idea directly: normalise, then compare.

    Complexity

    Let n be the number of lines and m the length of the longest. Time: every line is lowercased (O(m)) and searched, so the total is proportional to n times m, times the cost of the search. Space: one temporary lowercase string per line at a time, plus the result list, which holds the kept lines.

    Edge cases and common mistakes

    • Lowercasing only one side. line.Contains(lowerPattern) would miss "Error: 1" when the line has capitals, and line.ToLower().Contains(pattern) would fail for "ERR".
    • Returning the lowercase text. The expected output keeps the original casing.
    • Mixed case lines. "eRRor" matches "Err", since both lowercase to err.
    • No match. An empty list joins to "".

    Testing

    • Pattern "ERR" with ["Error: 1", "ok"] gives "Error: 1".
    • Pattern "ok" with ["OK", "Fine", "oK!"] gives "OK\noK!".
    • Pattern "zzz" with the same lines gives "".
    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