I just started with Go, and I'm having a little trouble accomplishing what I want to do. After loading a large text file in which each line begins with a word I want in my array, followed by single and multi-space delimited text I do not care about.
My first line of code creates an array of lines
lines := strings.Split( string( file ), "
" )
The next step would be to truncate each line which I can do with a split statement. I'm sure I could do this with a for loop but I'm trying to learn some of the more efficient operations in Go (compared to c/c++)
I was hoping I could do something like this
lines := strings.Split( (lines...), " " )
Is there a better way to do this or should I just use some type of for loop?
Using bufio.NewScanner
then word := strings.Fields(scanner.Text())
and slice = append(slice, word[0])
like this working sample code:
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
s := ` wanted1 not wanted
wanted2 not wanted
wanted3 not wanted
`
slice := []string{}
// scanner := bufio.NewScanner(os.Stdin)
scanner := bufio.NewScanner(strings.NewReader(s))
for scanner.Scan() {
word := strings.Fields(scanner.Text())
if len(word) > 0 {
slice = append(slice, word[0])
}
}
fmt.Println(slice)
}
Using strings.Fields(line)
like this working sample code:
package main
import "fmt"
import "strings"
func main() {
s := `
wanted1 not wanted
wanted2 not wanted
wanted3 not wanted
`
lines := strings.Split(s, "
")
slice := make([]string, 0, len(lines))
for _, line := range lines {
words := strings.Fields(line)
if len(words) > 0 {
slice = append(slice, words[0])
}
}
fmt.Println(slice)
}
output:
[wanted1 wanted2 wanted3]