Reading strings line by line, or word by word
There are many use cases for processing strings in a stream, such as when dealing with large text or user input. This recipe shows the use of bufio.Scanner
for this purpose.
How to do it...
- Use
bufio.Scanner
for reading lines, words, or custom blocks. - Create a
bufio.Scanner
instance - Set the split method
- Read scanned tokens in a for-loop
How it works...
The Scanner
works like an iterator – every call to Scan()
method will return true
if it parsed the next token, or false
if there are no more tokens. The token can be obtained by the Text()
method:
package main import ( "bufio" "fmt" "strings" ) const input = `This is a string that has 3 lines.` func main() { lineScanner := bufio.NewScanner(strings.NewReader(input)) line...