Start learning free

LESSON 12 OF 69 · PROJECTS: COMMAND-LINE TOOLS

wc in Go: A Mode Flag with strconv and fmt.Sprintf

Practice Read the full explanation

Combine the previous three versions of wc. Given a list of lines and a mode flag, return the requested count(s) as a string. This is our own simplified interface, not the real wc flags: the real tool combines flags (such as -lw) and pads its columns with spaces.

Function signature:

func wc(lines []string, mode string) string

Mode values:

  • "l" → line count, as a string.
  • "w" → word count (whitespace-separated tokens), as a string.
  • "c" → character count (lines only, no separating newlines), as a string.
  • "all" → lines + "\t" + words + "\t" + chars.

The "c" count is the one from v3 (the sum of the line lengths, no newlines). Any other mode value, for example "x" or "L" (modes are case-sensitive), gives the same result as "all". For an empty list, "l", "w" and "c" give "0" and "all" gives "0<TAB>0<TAB>0". The input is plain ASCII text.

Example:

Input: lines = ["hello", "world"], mode = "all"

Output: "2\t2\t10"

2 lines, 2 words (one per line), 10 characters total.


Compute all three counts in a single pass through lines, then branch on mode to pick the return value. strings.Fields handles the word count for you.

numLines := len(lines)
numWords := 0
numChars := 0
for _, line := range lines {
    numWords += len(strings.Fields(line))
    numChars += len(line)
}
Use strconv.Itoa(int) to convert numbers to strings.

The full solution:
func wc(lines []string, mode string) string {
    numLines := len(lines)
    numWords := 0
    numChars := 0
    for _, line := range lines {
        numWords += len(strings.Fields(line))
        numChars += len(line)
    }
    if mode == "l" { return strconv.Itoa(numLines) }
    if mode == "w" { return strconv.Itoa(numWords) }
    if mode == "c" { return strconv.Itoa(numChars) }
    return fmt.Sprintf("%d\t%d\t%d", numLines, numWords, numChars)
}

STEP 1 OF 10
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Wc V4 in Go, explained

    Problem overview

    This version combines the line, word and character counts into one function: wc(lines []string, mode string) string. The mode picks what to report, and the result is always a string, like the text a command-line tool prints.

    • "l" returns the number of lines, "w" the number of words and "c" the number of characters, each as text.
    • "all" returns the three counts in that order, separated by tab characters.
    • Any other mode behaves like "all". Modes are case-sensitive, so "L" falls into this group.

    For ["hello", "world"] and mode "all", the result is "2\t2\t10": 2 lines, 2 words, 10 characters. Characters are the sum of the line lengths, with no newlines counted, and the input is plain ASCII.

    Approach

    Compute all three numbers first, then choose which one to return. That is simpler than three separate passes, and it needs only one loop: the line count is just len(lines), while the words and characters are running totals updated for every line. After the loop, a few if checks decide the output. The "all" case is not tested at all: it is the fall-through at the bottom, which also handles every unknown mode.

    The lesson's earlier versions each answered one question with its own function. Here the three questions share one pass over the data, and the mode only selects which answer leaves the function. That keeps the code short, and the cost of computing a number nobody asked for is a few additions per line.

    Tracing the loop

    For ["hello world", "foo bar baz", ""], numLines is 3 from the start. The loop then updates the other two totals:

    LineLengthWordsnumWords afternumChars after
    "hello world"112211
    "foo bar baz"113522
    ""00522

    The totals are 3, 5 and 22, so mode "all" returns "3\t5\t22".

    Step by step

    1. Store the line count. numLines := len(lines) needs no loop.
    2. Start the word total and the character total at 0, each with :=. Both grow as lines are read.
    3. Loop over the lines with for _, line := range lines.
    4. Add the words. len(strings.Fields(line)) counts the whitespace-separated words, as in the word-count version.
    5. Add the characters. len(line) includes spaces and tabs, as in the character-count version.
    6. Return a single count for "l", "w" and "c". Each returns its number converted to text, one if per mode.
    7. Return all three as the last statement, formatted with tabs between them. It runs only when none of the earlier modes matched.

    The solution in Go

    func wc(lines []string, mode string) string {
        numLines := len(lines)
        numWords := 0
        numChars := 0
        for _, line := range lines {
            numWords += len(strings.Fields(line))
            numChars += len(line)
        }
        if mode == "l" { return strconv.Itoa(numLines) }
        if mode == "w" { return strconv.Itoa(numWords) }
        if mode == "c" { return strconv.Itoa(numChars) }
        return fmt.Sprintf("%d\t%d\t%d", numLines, numWords, numChars)
    }
    

    Go details worth knowing:

    • strconv.Itoa converts an int to a string. The conversion string(numLines) would not do this: it treats the number as a character code and gives the character with that code. That is why the function uses strconv.Itoa.
    • fmt.Sprintf builds a string. It works like Printf but returns the text instead of printing it. Each %d takes the next argument as a decimal integer, and \t in the format is a tab character.
    • One-line if blocks. Go requires braces around the body of an if, but they may sit on the same line, as in if mode == "l" { return ... }. There are no parentheses around the condition.
    • Strings compare with ==. It compares contents, so mode == "l" is true exactly when the text is l.
    • No else needed. Each branch returns, so the code after it only runs when the branch was skipped.

    The same choice can be written with a switch, which is common in Go once there are several fixed values to compare. After the loop, it would read:

    switch mode {
    case "l":
        return strconv.Itoa(numLines)
    case "w":
        return strconv.Itoa(numWords)
    case "c":
        return strconv.Itoa(numChars)
    default:
        return fmt.Sprintf("%d\t%d\t%d", numLines, numWords, numChars)
    }
    

    Its default case plays the part of the final return above, and a Go switch doesn't fall through from one case to the next, so no break is needed. It gives the same results for "l", "w", "c", "all" and "L". The lesson uses separate if statements, which is what the steps build.

    Complexity

    Time: O(n), where n is the total number of characters, because the loop scans each line once. The mode check is constant time. Space: O(w), at most the word slice of the longest line, which strings.Fields builds temporarily.

    Edge cases and common mistakes

    • Empty list. "l", "w" and "c" return "0", and "all" returns "0\t0\t0".
    • Unknown or differently cased mode. "x" and "L" give the same result as "all". For ["hello", "world"] both return "2\t2\t10".
    • Empty lines. They count as lines, add no words and no characters. For ["hello world", "foo bar baz", ""], mode "all" returns "3\t5\t22".
    • Converting with string(n). It compiles, but it returns a one-character string, not the digits.
    • Leaving a total unused. Go refuses to compile a variable that is declared and never read. Here all three, numLines, numWords and numChars, are read by the final return, so none of them triggers the error, even though a single-count mode ignores two of them.
    • Returning a number. The function's result type is string, so returning numLines directly is a compile error.

    Testing

    • ["hello", "world"] with "l" gives "2", with "w" gives "2", with "c" gives "10".
    • ["hello world", "foo bar baz", ""] with "all" gives "3\t5\t22".
    • [] with "all" gives "0\t0\t0".
    • ["hello", "world"] with "L" gives "2\t2\t10".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free