Start learning free

LESSON 25 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V1 in C++: Replacing One 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:

string tr(vector<string> lines, string fromChar, string toChar)

Example:

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

Output: "bXnXnX\nXpple"

When printed:
bXnXnX
Xpple

Walk each line character-by-character. For each char, append toChar[0] if it equals fromChar[0], otherwise append the original character.

for (int j = 0; j < lines[i].size(); j++) {
    if (lines[i][j] == fromChar[0]) result += toChar[0];
    else result += lines[i][j];
}


The full solution:
class Solution {
public:
    string tr(vector<string> lines, string fromChar, string toChar) {
        string result;
        for (int i = 0; i < lines.size(); i++) {
            if (i > 0) result += "\n";
            for (int j = 0; j < lines[i].size(); j++) {
                if (lines[i][j] == fromChar[0]) result += toChar[0];
                else result += lines[i][j];
            }
        }
        return result;
    }
};

STEP 1 OF 7
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Tr V1 in C++, explained

    Problem overview

    This is the first version of a small tr command. The method tr(vector<string> lines, string fromChar, string toChar) replaces every occurrence of one character with another in each line, then returns the lines joined by \n.

    Both fromChar and toChar are strings that hold a single ASCII character, taken literally: no escape sequences and no ranges. Upper and lower case are different characters. A line may be empty or may not contain the character at all. With {"banana", "apple"}, fromChar = "a" and toChar = "X", the result is "bXnXnX\nXpple".

    In the Unix tool, tr reads text and translates characters one by one. Here the text arrives as a vector of lines and the answer goes back as one string, which keeps the project easy to test. The statement limits the input to ASCII, and that matters in C++: a char is one byte, so a character outside ASCII, which takes several bytes in UTF-8, would be seen as several separate char values. With ASCII text, one byte is one character and the loops behave as expected.

    Approach

    The task is a character-by-character copy. Walk through the lines; inside each line walk through the characters; for each one, append either the replacement or the original character to a single result string. Nothing is modified in place, so the input stays intact and the function only builds new text.

    Newlines go between the lines, not after them. Before every line except the first, the code appends "\n". This is the same "separator before every item but the first" pattern that works for any join, and it gives no newline at the start and none at the end.

    The parameters arrive as strings, though they hold one character each. The characters themselves are fromChar[0] and toChar[0], the first character of each string. Comparing a char with fromChar[0] is a plain character comparison.

    On the example, result is "bXnXnX" once the first line has been processed. The second pass through the outer loop first appends a newline and then the characters of "apple", which leaves "bXnXnX\nXpple".

    Step by step

    1. Create an empty string named result, where the output is built.
    2. Loop over the lines with int i from 0 while i < lines.size().
    3. Add a newline when i > 0, in a one-line if. The first line gets none.
    4. Loop over the characters of lines[i] with int j from 0 while j < lines[i].size().
    5. If lines[i][j] == fromChar[0], append toChar[0] to result.
    6. Otherwise, in an else, append the original lines[i][j].
    7. Return result after both loops. The newlines are already in it.

    The solution in C++

    class Solution {
    public:
        string tr(vector<string> lines, string fromChar, string toChar) {
            string result;
            for (int i = 0; i < lines.size(); i++) {
                if (i > 0) result += "\n";
                for (int j = 0; j < lines[i].size(); j++) {
                    if (lines[i][j] == fromChar[0]) result += toChar[0];
                    else result += lines[i][j];
                }
            }
            return result;
        }
    };
    

    Points to watch:

    • Two levels of indexing. lines[i] is a string, so lines[i][j] is one char of it. The loop bounds use .size() of the right thing: lines.size() for the outer loop, lines[i].size() for the inner one.
    • Appending to a string. result += "\n" appends a string literal, result += toChar[0] appends a single char. Both forms of += work on std::string.
    • if and else without braces. Each branch has one statement, so braces are optional. If you add a second statement to a branch later, add the braces too.
    • Signed and unsigned. size() returns an unsigned value and i is an int. The comparison works for these sizes because the index never goes negative.

    A tidier version

    Once the steps are clear, the same logic can be shorter: take the two characters out of the strings once, and use a range-based loop and the conditional operator.

    char from = fromChar[0], to = toChar[0];
    string result;
    for (int i = 0; i < lines.size(); i++) {
        if (i > 0) result += "\n";
        for (char c : lines[i]) result += (c == from) ? to : c;
    }
    return result;
    

    It returns the same "bXnXnX\nXpple" for the example. The lesson's version keeps the indexes visible, which is easier to follow while you are learning the loops.

    Complexity

    The code visits each character of each line once and does a constant amount of work per character, so the time is proportional to the total number of characters, O(N), plus one step per line for the newline. The result string holds a copy of the text, so the extra space is also O(N).

    Edge cases and common mistakes

    • Case matters. {"Banana", "banana"} with fromChar = "B" and toChar = "-" gives "-anana\nbanana": only the capital B is replaced.
    • Empty lines. {"", "abc"} with "a" and "z" gives "\nzbc". The empty line is kept, so the result starts with a newline.
    • No match. {"hello"} with "z" and "y" returns "hello".
    • Spaces are characters too. {"a b c"} with " " and "_" gives "a_b_c".
    • Comparing the whole string. Writing lines[i][j] == fromChar compares a char with a string. The compiler rejects it with "no match for 'operator=='", because the two types can't be compared. Use fromChar[0].
    • Replacing in place and forgetting the newlines. The output is one string, and the line breaks must be added as "\n".
    • The same character on both sides. {"x"} with "x" and "x" returns "x": replacing a character with itself changes nothing.
    • Empty input. An empty vector returns "".

    Testing

    linesfromChar, toCharresult
    {"banana", "apple"}"a", "X""bXnXnX\nXpple"
    {"Banana", "banana"}"B", "-""-anana\nbanana"
    {"", "abc"}"a", "z""\nzbc"
    {"a b c"}" ", "_""a_b_c"
    {}"a", "b"""

    The next version builds on this one.

    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