Start learning free

LESSON 25 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V1 in C#: Replace a Character in Every Line

Practice Read the full explanation

Build a tiny version of the Unix tr command. Given a list of lines and two single characters fromChar and toChar, replace every occurrence of fromChar with toChar in each line, then return the lines joined by newline characters (\n).

Notes: fromChar and toChar are single ASCII characters, taken literally (no escapes like \, no ranges). Upper and lower case are different characters. A line may be empty, and may not contain fromChar at all.

Function signature:

public string Tr(List<string> lines, string fromChar, string toChar)

Example:

Input: lines = ["banana", "apple"], fromChar = "a", toChar = "X"

Output: "bXnXnX\nXpple"

When printed:
bXnXnX
Xpple

C#'s string.Replace(string, string) swaps EVERY occurrence. Apply it to each line and accumulate.

The full solution:
class Solution {
    public string Tr(List<string> lines, string fromChar, string toChar) {
        List<string> result = new List<string>();
        foreach (string line in lines) {
            result.Add(line.Replace(fromChar, toChar));
        }
        return string.Join("\n", result);
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Tr V1 in C#, explained

    Problem overview

    The method Tr imitates a tiny tr command. It receives a List<string> of lines and two strings, fromChar and toChar, each holding one ASCII character. It replaces every occurrence of fromChar with toChar in every line and returns the lines joined with "\n". Upper and lower case count as different characters. A line may be empty, or may not contain fromChar at all.

    For ["banana", "apple"] with fromChar = "a" and toChar = "X", the result is "bXnXnX\nXpple".

    Approach: translate each line, then join

    Each line is independent of the others, so the method handles one line at a time. It creates a list for the results, visits every line, adds the translated version and finally joins the list. The translation itself is a single call, because string has a Replace method that does the whole job.

    Step by step

    1. Create result, an empty List<string>. It starts empty and gains one translated line per loop pass.
    2. Write a foreach loop that takes each string line out of lines. No index is needed, since only the line itself matters.
    3. Add line.Replace(fromChar, toChar) to result. Replace takes the text to look for and the text to put in its place, and it changes every occurrence, not just the first.
    4. After the loop, return string.Join("\n", result). The separator goes between two lines only, so the output has no newline after the last line.

    The solution in C#

    class Solution {
        public string Tr(List<string> lines, string fromChar, string toChar) {
            List<string> result = new List<string>();
            foreach (string line in lines) {
                result.Add(line.Replace(fromChar, toChar));
            }
            return string.Join("\n", result);
        }
    }
    

    The C# details:

    • Strings are immutable. Replace never changes line. It returns a new string, and the loop stores that new string in result. Writing line.Replace(fromChar, toChar); as a statement on its own would throw the result away.
    • Replace has a string version and a char version. Here the parameters are strings, so the Replace(string, string) overload runs. Its text comparison is ordinal and case-sensitive, so "a" does not match "A".
    • An empty search text is an error. "a".Replace("", "X") throws an ArgumentException. The lesson says fromChar is a single character, so that case does not occur.
    • foreach cannot assign to its variable. Replacing line inside the loop wouldn't compile, which is another reason to collect results in a second list.

    Complexity

    Let L be the total number of characters across all lines. Time: O(L), because each line is scanned once and rebuilt. Space: O(L) for the translated lines and the joined string.

    Edge cases and common mistakes

    • Empty line. "".Replace("a", "X") is "", and the empty line stays in the output. For ["a", "", "a"] with "a" and "X" the result is "X\n\nX".
    • No match. A line without fromChar comes back unchanged.
    • Case. With fromChar = "a", the line "Apple" keeps its capital A, so ["banana", "Apple", ""] gives "bXnXnX\nApple\n".
    • Special characters. The match is literal. ["a.b.c"] with "." and "-" gives "a-b-c", and the dot is not a wildcard.
    • Ignoring the return value. Because strings are immutable, Replace must be assigned or added somewhere.
    • Joining with the wrong separator. string.Join takes the separator first, then the list.

    Testing

    • ["banana", "apple"], "a", "X" gives "bXnXnX\nXpple".
    • ["a.b.c"], ".", "-" gives "a-b-c".
    • ["banana", "Apple", ""], "a", "X" gives "bXnXnX\nApple\n".
    • [], "a", "X" 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