Go文件中读取一行字符串,统计英文、数字、空格以及其他字符的数量。

package main

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

// 结构体计数
type CharCount struct{
	ChCount int
	NumCount int
	SpaceCount int
	OtherCount int
}


// 字符计数
func classifyChars(str string)  {
	
	var count CharCount

	var runeArr = []rune(str)

	for _, v := range runeArr {
		switch  {
		case v >= 'a' && v <= 'z':
			fallthrough
		case v >='A' && v <= 'Z':
			count.ChCount++
		case v == ' ' || v == '\t':
			count.SpaceCount++
		case v >= '0' && v <= '9':
			count.NumCount++
		default:
			count.OtherCount++
		}
	}

	fmt.Printf("char count:%d\n", count.ChCount)
	fmt.Printf("num count:%d\n", count.NumCount)
	fmt.Printf("space count:%d\n", count.SpaceCount)
	fmt.Printf("other count:%d\n", count.OtherCount)
}

func main()  {
	file,err :=os.Open("D:/test.log")
	if err!=nil{
			fmt.Println("read file err:",err)
	}
	defer file.Close()

	reader := bufio.NewReader(file)
	str,err :=reader.ReadString('\n')

	if err !=nil{
		fmt.Println("read string failed,err:",err)
		return
	}

	classifyChars(str)
}

你可能感兴趣的:(Go)