go语言渐入佳境[5]-printf格式化打印

输入:

下面的功能为获取键盘输入存储到map表中,打印数量超过1的字符串与个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
"bufio"
"fmt"
"os"
)

func main() {
counts := make(map[string]int)
input := bufio.NewScanner(os.Stdin)
for i:=0;input.Scan();i++{
counts[input.Text()]++
if i>5{
break;
}
}
// NOTE: ignoring potential errors from input.Err()
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}

输入改进2:

即可获取键盘输入,又可获取文件的输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main

import (
"bufio"
"fmt"
"os"
)

func main() {
counts := make(map[string]int)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts)
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
continue
}
countLines(f, counts)
f.Close()
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}

func countLines(f *os.File, counts map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
// NOTE: ignoring potential errors from input.Err()
}

输入改进3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
"fmt"
"io/ioutil"
"os"
"strings"
)

func main() {
counts := make(map[string]int)
for _, filename := range os.Args[1:] {
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "dup3: %v\n", err)
continue
}
for _, line := range strings.Split(string(data), "\n") {
counts[line]++
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}

golang输出的格式化打印

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main

import "fmt"

func main(){


//通用的格式
str:="jonson"

fmt.Printf("%T,%v\n",str,str)

//布尔
var booeanl = true
fmt.Printf("%T,%t\n",booeanl,booeanl)

//特殊字符

fmt.Printf("%%\n")
fmt.Printf("\"\n")
fmt.Printf("\\\n")


//整数

fmt.Printf("%T,%d\n",123,123)
fmt.Printf("%T,%6d\n",123,123) //6代表长度
fmt.Printf("%T,%06d\n",123,123)//0代表填充0
fmt.Printf("%T,%b\n",123,123) //二进制
fmt.Printf("%T,%o\n",123,123) //8进制
fmt.Printf("%T,%x\n",123,123) //16进制
fmt.Printf("%T,%#x\n",123,123) //前面加上0x
fmt.Printf("%T,%#o\n",123,123)//前面加上0

fmt.Printf("%T,%#X\n",123,123) //大写的X代表字母会大写

fmt.Printf("% d,% d\n",123,-123) //空格代表正数前方会预留一个空格

// 浮点数
fmt.Printf("%T,%f\n",123.456,123.456)
fmt.Printf("%T,%10f\n",123.456,123.456)//长度
fmt.Printf("%T,%.1f\n",123.456,123.456) //保留的小数位数
fmt.Printf("%T,%10.2f\n",123.456,123.456)

//字符串
fmt.Printf("%T,%s\n","jonson","jonson")

//字符串
fmt.Printf("%T,%c\n",'c',97)
}