Start learning free

LESSON 3 OF 70 · PROJECTS: COMMAND-LINE TOOLS

cat v3 in Kotlin: 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:

fun 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 {
    fun showAllCat(lines: List<String>): String {
        val sb = StringBuilder()
        for (i in 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

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Cat V3 in Kotlin, explained

    Problem overview

    Some characters can't be seen. A tab looks like a few spaces, and trailing spaces at the end of a line look like nothing. The -A flag of cat makes them visible. In this version you write a new function, fun showAllCat(lines: List<String>): String, that does two things to every line:

    • every tab character (\t) becomes the two visible characters ^I;
    • a literal $ is added at the end of the line, so any trailing spaces show up before it.

    The rows are then joined with newlines, with no newline after the last row. A blank line becomes just $, and an empty list gives an empty string. Only tabs and line ends are handled here; the real command also shows other control characters, but this lesson doesn't.

    For ["hello\tworld", "foo"] the result is "hello^Iworld$\nfoo$". For ["a\t", "", "x "] it is "a^I$\n$\nx $".

    Approach

    The shape is the same as the numbered version: loop over the lines by position, put a newline in front of every row except the first, and collect everything in a StringBuilder. Only the row itself changes. Instead of formatting a number, you transform the line with replace and then add the $ marker.

    Why the two markers help

    Tabs and spaces can look identical on screen, yet a program that reads the text treats them differently. After -A the difference is on the page: a line such as "a\t" shows as a^I$, which tells you it ends with a tab, while "a " shows as a $, which tells you it ends with a space. A line that ends with the marker right after its last visible character has no trailing whitespace at all.

    The rule for each row is the same whatever the line holds: transform the text, then add the marker. Keeping the two steps in that order, and keeping the newline logic separate from both, is what makes the function short.

    Step by step

    1. Create val sb = StringBuilder() to collect the output.
    2. Loop over lines.indices. The index tells you which line to read and whether it is the first.
    3. Check i > 0 and append "\n" inside it. The newline separates two rows, so the first row gets none.
    4. Append the line with its tabs swapped. lines[i].replace("\t", "^I") returns a new string in which every tab is replaced.
    5. Append "$" after the line. It goes after the replaced text, so trailing spaces stay in front of it.
    6. Return sb.toString() after the loop.

    The solution in Kotlin

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

    Printing the results of a few calls shows the markers:

    hello^Iworld$
    foo$
    a^I$
    $
    x  $
    ^I^I$
    

    The first two rows come from ["hello\tworld", "foo"], the next three from ["a\t", "", "x "] and the last from ["\t\t"]. Calling the function on an empty list returns "", which prints as an empty line.

    Kotlin details worth knowing

    • A lone $ in a string is fine. Kotlin uses $name and ${expression} for string templates, but a dollar sign that isn't followed by a name or a brace is an ordinary character. That is why "$" compiles and holds one dollar sign. If you ever need a dollar sign right before a name, write \$: "a\$b" is the text a$b.
    • "\t" is one character. The two characters in the source, a backslash and a t, stand for a single tab. The replacement "^I" has two characters, a caret and a capital I.
    • replace doesn't change the original. Strings are immutable, so replace returns a new string. Calling lines[i].replace(...) and throwing away the result would change nothing.
    • replace replaces every occurrence. "\t\t" becomes "^I^I"; you don't need a loop for several tabs.

    Edge cases and common mistakes

    • Forgetting the marker on blank lines. An empty string still gets its $, so the row is "$" and the line isn't lost.
    • Putting $ before the replacement. The marker must come after the line, or trailing spaces would sit after it and no longer be visible.
    • Stripping trailing spaces. Don't trim the line. Showing them is the point: "x " becomes "x $".
    • A newline after the last row. The newline is a separator that goes before every row but the first. The result for a single line "foo" is "foo$" with nothing after it.
    • Replacing spaces too. Only tabs change. Ordinary spaces stay as they are.

    Testing

    Try these inputs in the editor above and compare:

    • ["\t\t"] gives "^I^I$": two tabs, two markers, one end marker.
    • ["cost: 5"] gives "cost: 5$": a line without tabs only gains the marker, and the dollar sign in the output is just a character.
    • [] gives "": no rows, so not even a marker.
    • ["a\r"] keeps its carriage return as it is, because only tabs are replaced in this version.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free