Skip to content

Quick Notes

Updated View as Markdown

字符串操作

判断字符串是否以特定前缀开头

if strings.HasPrefix(str, "Start With..."){fmt.Println("Yes!")}

判断字符串是否以特定前缀结尾

if strings.HasSuffix(str, "Start With..."){fmt.Println("Yes!")}

判断包含

if strings.Contains(str, "Contains..."){fmt.Println("Yes!")}

读取文件

逐行阅读

package main

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

func main() {
	file, err := os.Open("file.txt")
	if err != nil {
		fmt.Println(err)
		file.Close()
		os.Exit(1)
	}
	sc := bufio.NewScanner(file)
	sc.Buffer(make([]byte, 64*1024), 1024*1024) // 可选: 限制行大小
	var line int
	for sc.Scan() {
		line++
		content := sc.Text()
		fmt.Println(line, ": ", content)
	}
	if sc.Err() != nil {
		fmt.Println(sc.Err())
		file.Close()
		os.Exit(1)
	}

}

Navigation

Type to search…

↑↓ navigate↵ selectEsc close