美文网首页
使用来自ByteCounter的思路, 实现一个针对对单词和行数

使用来自ByteCounter的思路, 实现一个针对对单词和行数

作者: 韩小禹 | 来源:发表于2020-04-17 17:04 被阅读0次
/*
 * @Description:
 * @Author: ethan
 * @Date: 2020-04-17 15:04:38
 * @LastEditTime: 2020-04-17 17:03:03
 * @LastEditors: ethan
 */
package main

import (
    "bufio"
    "fmt"
    "strings"
)

type ByteCounter int

func (c *ByteCounter) Write(p []byte) (int, error) {
    *c += ByteCounter(len(p))
    return len(p), nil
}

type WordsCounter int

func (w *WordsCounter) Write(p []byte) (int, error) {
    str := strings.NewReader(string(p)) //strings.NewReader函数实现了io.Reader接口,所以可以使用
    bs := bufio.NewScanner(str)         //NewScanner需要传入一个实现了Io.reader接口的参数
    bs.Split(bufio.ScanWords)           //bufio.ScanWords 是用于 Scanner类型的分隔函数,根据文档中提到的bufio.ScanWords顺着接口一层层往上找
    sum := 0
    for bs.Scan() {
        sum++
    }
    *w += WordsCounter(sum)
    return sum, nil
}

type LinesCouter int

func (l *LinesCouter) Writer(p []byte) (int, error) {
    lines := strings.NewReader(string(p))
    bs := bufio.NewScanner(lines)
    bs.Split(bufio.ScanLines)
    sum := 0
    for bs.Scan() {
        sum++
    }
    *l += LinesCouter(sum)
    return sum, nil
}

func main() {
    var c ByteCounter
    c.Write([]byte("hello"))
    c.Write([]byte("hello"))
    fmt.Println(c)

    var w WordsCounter
    strs := map[string]string{
        "a": "hello world you",
        "b": "hello world you",
    }
    for _, v := range strs {
        res, _ := w.Write([]byte(v))
        fmt.Println(res)
    }
    fmt.Println(w)

    lines := "a\nb\nc"
    line1 := "aa\nbb\ncc"
    var l LinesCouter
    l.Writer([]byte(lines))
    l.Writer([]byte(line1))
    fmt.Println(l)

}

相关文章

网友评论

      本文标题:使用来自ByteCounter的思路, 实现一个针对对单词和行数

      本文链接:https://www.haomeiwen.com/subject/iomyvhtx.html