Ver código fonte

build the basic word counter

simon 9 meses atrás
commit
12306d9fbb

+ 1 - 0
.gitignore

@@ -0,0 +1 @@
+.DS_Store

+ 2 - 0
rggo/firstProgram/wc/.gitignore

@@ -0,0 +1,2 @@
+.dist
+wc

+ 3 - 0
rggo/firstProgram/wc/go.mod

@@ -0,0 +1,3 @@
+module pragprog.com/rggo/firstProgram/wc
+
+go 1.21.6

+ 27 - 0
rggo/firstProgram/wc/main.go

@@ -0,0 +1,27 @@
+package main
+
+import (
+	"bufio"
+	"fmt"
+	"io"
+	"os"
+)
+
+func main() {
+	// Calling the count function to count the number of words
+	// received from the standard input and printing it out
+	fmt.Println(count(os.Stdin))
+}
+
+func count(r io.Reader) int {
+	scanner := bufio.NewScanner(r)
+	// Split sets the split function for the Scanner.
+	// The default split function is ScanLines.
+	scanner.Split(bufio.ScanWords)
+	wc := 0
+	// For every word scanned, increment the counter
+	for scanner.Scan() {
+		wc++
+	}
+	return wc
+}

+ 16 - 0
rggo/firstProgram/wc/main_test.go

@@ -0,0 +1,16 @@
+package main
+
+import (
+	"bytes"
+	"testing"
+)
+
+func TestCountWords(t *testing.T) {
+	b := bytes.NewBufferString("hello world world2 world3 world4\n")
+
+	exp := 5
+	res := count(b)
+	if res != exp {
+		t.Errorf("Expected %d, got %d instead.\n", exp, res)
+	}
+}