Start learning free

LESSON 11 OF 69 · PROJECTS: COMMAND-LINE TOOLS

wc Character Count in Go: Summing len of Each Line

Practice Read the full explanation

Build a tiny version of the character count of the Unix wc command. Given a list of lines, return the total number of characters across all lines as an integer.

Convention: count only the characters in each line — do not count the implicit newlines that separate them. Spaces and tabs inside a line count as one character each.

Note: this is a simplified version. The real wc -m also counts the newlines, and the real wc -c counts bytes, not characters. Here the answer is simply the sum of the line lengths. The input is plain ASCII text (other alphabets are counted differently by different languages).

Function signature:

func countChars(lines []string) int

Example:

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

Output: 10

"hello" has 5 chars and "world" has 5 chars, for a total of 10.

An empty line adds 0, and an empty list of lines gives 0.


Loop through the lines and accumulate len(lines[i]) into an int running total.

The full solution:
func countChars(lines []string) int {
    total := 0
    for i := 0; i < len(lines); i++ {
        total += len(lines[i])
    }
    return total
}

STEP 1 OF 4
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Wc V3 in Go, explained

    Problem overview

    The function countChars takes a slice of strings, lines, and returns the total number of characters across all of them. This is a simplified take on the Unix wc command: only the characters inside each line are counted, and the newlines that would separate the lines are not. Spaces and tabs count as one character each.

    For ["hello", "world"] the answer is 10, because each word has 5 characters. An empty line adds 0, and an empty slice gives 0. The input is plain ASCII.

    Approach

    The structure is the same as in the word-count version: keep a running total, visit every line, add something about that line. What changes is what gets added. Here it is the length of the line, which in Go is len(line).

    The loop is also written differently. Instead of range, it counts the position i from 0 up to len(lines) - 1 and reads lines[i]. Both styles do the same work. The indexed form is the one to reach for when the position itself matters, and it is worth knowing because Go has no while loop: for in its three-part form covers it.

    Step by step

    1. Create the total. total := 0 declares an int. It is the answer for an empty slice, since the loop then doesn't run.
    2. Write the loop header. for i := 0; i < len(lines); i++ has three parts: the start, the condition checked before each pass, and the step after each pass. The last valid position is len(lines) - 1, so the condition uses <, not <=.
    3. Add the length. Inside the loop, len(lines[i]) is the size of the current line, and total += adds it.
    4. Return the total after the loop's closing brace, so it runs once, after all lines are counted.

    The solution in Go

    func countChars(lines []string) int {
        total := 0
        for i := 0; i < len(lines); i++ {
            total += len(lines[i])
        }
        return total
    }
    

    The detail that matters most is what len measures on a string. len counts bytes, not characters. For ASCII text the two are equal, which is why this solution passes the lesson's tests. With other alphabets they differ: len("héllo") is 6, because é takes two bytes in UTF-8, although the word has 5 characters. To count characters (runes) you would use utf8.RuneCountInString from the unicode/utf8 package, or len([]rune(s)). The lesson only gives ASCII, so len is enough.

    Other notes:

    • No newline is added. The total is the sum of the line lengths and nothing else, so ["hello", "world"] gives 10, not 11.
    • Tabs count once. ["a b", "\tx", ""] gives 5: three characters, then two (a tab and x), then none.
    • i++ is a statement. In Go it can't be used inside an expression, and there is no ++i.

    Complexity

    Time: O(m), where m is the number of lines. In Go, len of a string reads a stored size and doesn't scan the characters, so each line costs constant time and the loop does one step per line.

    Space: O(1). Only total and the loop counter are kept.

    Edge cases and common mistakes

    • Empty slice or empty lines. Both add nothing, so the answer is 0 when there are no characters.
    • Off-by-one in the loop. Writing i <= len(lines) reads lines[len(lines)], which is out of range and makes the program panic.
    • Counting separators. The real wc counts the newline between lines; this lesson doesn't, so don't add 1 per line.
    • Non-ASCII text. Because len returns bytes, the total for ["héllo"] is 6, not 5.

    Testing

    • ["hello", "world"] gives 10.
    • ["a b", "\tx", ""] gives 5.
    • [] gives 0.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free