Skip to main content
3 of 4
itty bitty typeroni
Alex A.
  • 24.7k
  • 5
  • 38
  • 119

Reimplement the wc coreutil

This challenge is similar to this old one, but with some unclear parts of the spec hammered out and less strict I/O requirements.


Given an input of a string consisting of only printable ASCII and newlines, output its various metrics (byte, word, line count).

The metrics that you must output are as follows:

  • Byte count. Since the input string stays within ASCII, this is also the character count.

  • Word count. This is wc's definition of a "word:" any sequence of non-whitespace. For example, abc,def"ghi" is one "word."

  • Line count. This is self-explanatory. The input will always contain a trailing newline, which means line count is synonymous with "newline count." There will never be more than a single trailing newline.

The output must exactly replicate the default wc output (except for the file name):

llama@llama:~$ cat /dev/urandom | tr -cd 'A-Za-z \n' | head -90 > example.txt
llama@llama:~$ wc example.txt
  90  165 5501 example.txt

Note that the line count comes first, then word count, and finally byte count. Furthermore, each count must be left-padded with spaces such that they are all the same width. In the above example, 5501 is the "longest" number with 4 digits, so 165 is padded with one space and 90 with two. Finally, the numbers must all be joined into a single string with a space between each number.

Since this is , the shortest code in bytes will win.

(Oh, and by the way... you can't use the wc command in your answer. In case that wasn't obvious already.)

Test cases (\n represents a newline; you may optionally require an extra trailing newline as well):

"a b c d\n" -> "1 4 8"
"a b c d e f\n" -> " 1  6 12"
"  a b c d e f  \n" -> " 1  6 16"
"a\nb\nc\nd\n" -> "4 4 8"
"a\n\n\nb\nc\nd\n" -> " 6  4 10"
"abc123{}[]()...\n" -> " 1  1 16
"\n" -> "1 0 1"
"   \n" -> "1 0 4"
"\n\n\n\n\n" -> "5 0 5"
"\n\n\na\nb\n" -> "5 2 7"
Doorknob
  • 71.8k
  • 20
  • 143
  • 385