Now it's time to implement your own simple word counter! Let's create a function that counts the number of words in text by analyzing a slice of bytes.
Given text stored as a slice of bytes (like when reading from a file), how do we count the words?
For example, this text has 5 words:
"Hello world from the matrix"
Your challenge is to figure out how to count them!
When you read text from a file, it comes as a slice of bytes ([]byte). Each character is represented as a byte:
text := []byte("Hello world")
fmt.Println(text)
// Output: [72 101 108 108 111 32 119 111 114 108 100]
Each number represents a character. For example, 72 is 'H', 101 is 'e', and so on.
Use range to iterate over each byte in the slice:
data := []byte("Hello world")
for _, b := range data {
fmt.Println(b)
}
// Output: prints each byte value (72, 101, 108, 108, 111, 32, ...)
The first value from range is the index (which we ignore with _), and the second is the actual byte value.
You can compare a byte directly to a character using single quotes:
data := []byte("Hello world")
for _, b := range data {
if b == ' ' {
fmt.Println("Found a space!")
}
if b == 'H' {
fmt.Println("Found an H!")
}
}
Important: Use single quotes ' ' for characters, not double quotes " " (which are for strings).
Before you start coding, think about:
"Hello world from the matrix" - what pattern do you notice?Implement the countWords function that accepts a slice of bytes and returns the number of words.
The function signature is:
func countWords(data []byte) int {
// Your code here
}
Test cases:
[]byte("Goku Vegeta Gohan") should return 3[]byte("Hello world") should return 2[]byte("Hi") should return 1