Start learning free

LESSON 3 OF 70 · PROJECTS: COMMAND-LINE TOOLS

cat v3 in Scala: Show Tabs and Line Ends (-A)

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:

def showAllCat(lines: List[String]): String

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 "$". Put a "\n" between lines.

String.replace swaps every occurrence: lines(i).replace("\t", "^I").

The full solution:
class Solution {
    def showAllCat(lines: List[String]): String = {
        val sb = new StringBuilder()
        for (i <- lines.indices) {
            if (i > 0) {
                sb.append("\n")
            }
            sb.append(lines(i).replace("\t", "^I"))
            sb.append("$")
        }
        return sb.toString()
    }
}

STEP 1 OF 7
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Cat V3 in Scala, explained

    Problem overview

    This version adds the -A flag of cat as a new function, showAllCat. It takes a List[String] and makes whitespace visible. Every tab character becomes the two characters ^I, and every line ends with a literal $, so trailing spaces become obvious. The lines are joined with newlines, with no newline after the last one.

    For ["hello\tworld", "foo"] the result is "hello^Iworld$\nfoo$". For ["a\t", "", "x "] it is "a^I$\n$\nx $": the tab became ^I, the blank line is just $, and the two spaces in x now sit right in front of the marker. An empty list gives an empty string.

    Real cat -A also shows other control characters and non-ASCII bytes. This version handles only tabs and line ends.

    Approach

    Each line is transformed on its own, in two small steps: swap its tabs for ^I, then add $ after it. Then the transformed lines are joined. The joining follows the same pattern as the previous version: a newline goes in front of every row except the first, so the output never ends with a newline.

    The loop walks the positions with lines.indices, because it needs to know whether the current line is the first one. A StringBuilder collects the pieces.

    The $ is appended after the line has been changed, not before. That is what makes trailing spaces visible: they are part of the line, so they come out before the marker.

    Take the second example, ["a\t", "", "x "], one line at a time. The first line "a\t" has its tab replaced and becomes "a^I", then $ is appended to give "a^I$". The empty line has nothing to replace, so only the marker is added: "$". The third line "x " has no tab, so it keeps its two trailing spaces and ends up as "x $". Joined with newlines, these three rows are the result shown above. Each row is finished on its own, so no line can affect how its neighbours look.

    Without the marker, a line with trailing spaces and a line without them look identical on screen. With it, the difference is visible: x$ against x $. Tabs have the same problem, since a tab and a run of spaces can look alike, so ^I tells them apart.

    Step by step

    1. Create a StringBuilder named sb for the output.
    2. Loop over the positions with for (i <- lines.indices).
    3. Check i > 0. Only rows after the first need a separator in front of them.
    4. Append a newline inside that check.
    5. Append the line with its tabs replaced. The string method replace swaps every occurrence of one piece of text for another: lines(i).replace("\t", "^I").
    6. Append "$" still inside the loop, after the line.
    7. Return the text with sb.toString(), after the loop.

    The solution in Scala

    class Solution {
        def showAllCat(lines: List[String]): String = {
            val sb = new StringBuilder()
            for (i <- lines.indices) {
                if (i > 0) {
                    sb.append("\n")
                }
                sb.append(lines(i).replace("\t", "^I"))
                sb.append("$")
            }
            return sb.toString()
        }
    }
    

    Details worth knowing:

    • replace("\t", "^I") replaces every tab, not only the first, and returns a new string. Strings can't be changed in place, so the original line is untouched.
    • In "\t" the two source characters stand for one tab character. The replacement "^I" is plain text: a caret and a capital I, with no special meaning to Scala.
    • The "$" is an ordinary string here. Scala only gives $ a meaning inside interpolated strings such as s"...", which this code doesn't use.
    • replace with two strings matches the text literally, not as a pattern. "a.b.c".replace(".", "-") gives "a-b-c", so a character such as . is safe to replace.
    • Both append calls add to the same builder, so the order of the calls is the order in the output.

    A shorter way to write it

    The loop and the first-row check exist only to place the separators. If you transform every line first and join afterwards, mkString does that placement for you:

    lines.map(_.replace("\t", "^I") + "$").mkString("\n")
    

    On List("a\t", "", "x ") this gives "a^I$\n$\nx $", the same as the lesson's solution, and on an empty list it gives "". The lesson uses the explicit loop, which makes each step visible.

    Edge cases and common mistakes

    • A blank line. It still gets its marker. List("") gives "$", not an empty string.
    • Empty list. The loop never runs and the result is "". This differs from List(""), which has one empty line.
    • Several tabs. "\t\t" becomes ^I^I, so the line List("\t\t") gives "^I^I$".
    • Trailing spaces. They stay in the line, and the marker lands after them: "x $". Trimming the line would hide the very thing this flag shows.
    • Marker before the line. Appending "$" first would put it at the start of each row.
    • A trailing newline. Appending "\n" after every row, instead of before every row but the first, leaves an extra newline at the end.

    Testing

    InputResult
    List("hello\tworld", "foo")"hello^Iworld$\nfoo$"
    List("a\t", "", "x ")"a^I$\n$\nx $"
    List("")"$"
    List("\t\t")"^I^I$"
    List()""
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free