Golang bufio.Scanner 介绍
作者:互联网
目录
Scanner,用于处理数据读取的简单任务,支持按行、按单词等方式读取,一般用于一些简单的读取场景。注意:Scanner 默认是按行读取,可以调用 Split 方法修改读取方式。
1. 接收标准输入
scanner := bufio.NewScanner(os.stdin)
for scanner.Scan() {
fmt.Println(scanner.Text)
}
2. 接收文件内容
f, _ := os.Open("xxx.txt")
scanner := bufio.NewScanner(f)
for scanner.Scan() {
// ...
}
func printFile(filename string) {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
func main() {
printFile("users.txt")
}
3. 示例
// 接收用户输入的账号密码
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
Login()
}
func Login() (map[string]string, map[string]string) {
user := map[string]string{}
pass := map[string]string{}
fmt.Println("欢迎光临!")
fmt.Println("请输入用户名:")
LoginUser := bufio.NewScanner(os.Stdin)
if LoginUser.Scan() {
user["userName"] = LoginUser.Text()
} else {
user["userName"] = "输入错误"
}
fmt.Println("请输入登录密码:")
LoginPassword := bufio.NewScanner(os.Stdin)
if LoginPassword.Scan() {
pass["PassWord"] = LoginPassword.Text()
} else {
pass["PassWord"] = "您输入错误"
}
return user,pass
}
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
str := "A vegan woman in Australia is taking her neighbor to court because he keeps -- wait for it -- barbecuing stuff in his backyard. The smell of the meat and fish he's been cooking has apparently prevented her from enjoying her own backyard."
scanner := bufio.NewScanner(strings.NewReader(str))
// 设置分词方式(按行读取)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
fmt.Println("-------------------")
// 按单词读取
wordScanner := bufio.NewScanner(strings.NewReader(str))
wordScanner.Split(bufio.ScanWords)
for wordScanner.Scan() {
fmt.Println(wordScanner.Text())
}
}
https://studygolang.com/articles/21198
https://blog.csdn.net/weixin_29662775/article/details/112099878
https://www.nuomiphp.com/eplan/676180.html
标签:string,NewScanner,fmt,Golang,Println,bufio,scanner,Scanner 来源: https://www.cnblogs.com/shenyuanhaojie/p/16086770.html