Start learning free

LESSON 3 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat v3 in Java: Show Tabs and Line Ends with replace

Practice Read the full explanation

Now build the -A flag of the cat tool, as a new function. It makes whitespace visible: every tab character (\t) is replaced by the two characters ^I and every line ends with a literal $ marker (so trailing spaces become obvious). Lines are then joined with newlines.

Note: real cat -A also shows other control characters (such as ^M) and non-ASCII bytes; this version only handles tabs and line ends, like cat -T -E. A blank line becomes just $, and an empty list gives an empty string.

Function signature:

public String showAllCat(List<String> lines)

Example:

Input: lines = ["hello\tworld", "foo"]

Output: "hello^Iworld$\nfoo$"

When printed:
hello^Iworld$
foo$

Another example (a blank line, trailing spaces):

Input: lines = ["a\t", "", "x  "]

Output: "a^I$\n$\nx  $"

When printed:
a^I$
$
x  $

Use a StringBuilder and walk the lines by index. For each line, replace tabs with "^I", append the result, then append "$". Don't forget the "\n" separator between lines.

Java's String.replace(CharSequence, CharSequence) handles the literal swap:
sb.append(lines.get(i).replace("\t", "^I"));
sb.append("$");


The full solution:
class Solution {
    public String showAllCat(List<String> lines) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines.size(); i++) {
            if (i > 0) sb.append("\n");
            sb.append(lines.get(i).replace("\t", "^I"));
            sb.append("$");
        }
        return sb.toString();
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Cat V3 in Java, explained

    Problem overview

    The third version of the cat tool adds the -A flag as a new method, showAllCat(List<String> lines). It makes invisible characters visible. Every tab character becomes the two characters ^I, and every line ends with a literal $, so trailing spaces show up right before it. The lines are then joined with \n.

    For ["hello\tworld", "foo"] the result is "hello^Iworld$\nfoo$", which prints as:

    hello^Iworld$
    foo$
    

    A blank line becomes just $, and an empty list gives an empty string. Only tabs and line ends are handled here; other control characters are left alone.

    Approach: transform each line, then join

    Each line is rewritten on its own, in two small moves: swap the tabs, then add the marker. A StringBuilder collects the rows, and a newline goes between two rows, never after the last one. The marker is part of every row, so a newline is only a separator and the result has no trailing newline.

    The loop runs over positions because the code has to know whether it is on the first row: that row gets no newline in front of it.

    Step by step

    1. Create the builder. Declare a StringBuilder named sb for the changed rows.
    2. Loop by position. Use a for loop with int i from 0 while i < lines.size(). The index picks the line and tells whether it is the first.
    3. Separate the rows. Append "\n" when i > 0, as a one-line if.
    4. Append the line with its tabs swapped. replace("\t", "^I") returns a copy in which every tab is replaced by ^I. The rest of the line stays as it was.
    5. Append the marker. Add "$" after the line text, inside the loop.
    6. Return the text. After the loop, return sb.toString(). It runs once, after every row is in.

    The solution in Java

    class Solution {
        public String showAllCat(List<String> lines) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < lines.size(); i++) {
                if (i > 0) sb.append("\n");
                sb.append(lines.get(i).replace("\t", "^I"));
                sb.append("$");
            }
            return sb.toString();
        }
    }
    

    The Java details worth a closer look:

    • Strings are immutable. replace never changes the string it is called on; it returns a new one. Writing r.replace("\t", "^I"); on its own line and ignoring the result leaves r untouched: for r = "a\tb" it still holds a\tb afterwards. That is why the result is passed straight to sb.append.
    • replace replaces every occurrence. Despite its name, String.replace(CharSequence, CharSequence) handles all matches, not just the first. A line holding two tabs and an x becomes ^I^Ix.
    • The arguments are plain text. replace takes literal strings, not patterns. The ^ in "^I" has no special meaning, which is not the case in replaceAll, whose first argument is a regular expression.
    • "\t" is one character. In the source, the two characters \t are an escape for a single tab. The replacement "^I" contains no backslash, so it is simply a caret and a capital I.
    • Appending twice. sb.append(...) accepts a String, so the line and the marker are two separate calls on the same builder.

    Complexity

    Time: O(total length). Each line is scanned once by replace and copied into the builder once. lines.get(i) is constant time for an ArrayList.

    Space: O(total length) for the builder and the returned string. Each tab grows by one character, and each line grows by one for the marker.

    Edge cases and common mistakes

    • Discarding the result of replace. Calling lines.get(i).replace("\t", "^I"); as a statement of its own changes nothing, because strings can't change. The tabs stay in the output.
    • Trailing spaces. The marker goes after the line, so "x " becomes x $, with both spaces kept. Trimming the line would remove exactly what the flag is meant to reveal.
    • Blank lines. An empty string still gets its marker: [""] gives "$", so a list holding one blank line is different from an empty list, which gives "".
    • A newline after every row. Appending "\n" at the end of each iteration adds a trailing newline that the expected result doesn't have.
    • Only tabs are changed. A line made of two tabs and an x gives ^I^Ix$. Other characters pass through as they are.

    Testing

    The results below come from running the solution:

    • ["hello\tworld", "foo"] gives "hello^Iworld$\nfoo$".
    • ["a\t", "", "x "] gives "a^I$\n$\nx $".
    • [] gives "".
    • [""] gives "$".
    • ["\t\tx"] gives "^I^Ix$".
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free