方法一
經過ASCII碼錶判斷並統計正則表達式
package main import "fmt" func charactortype() { var s2 string = "112aaaaFGG123 *&^%" var e,s,d,o int for i := o; i < len(s2); i++ { switch { case 64 < s2[i] && s2[i] < 91: e += 1 case 96 < s2[i] && s2[i] < 123: e += 1 case 47 < s2[i] && s2[i] < 58: d += 1 case s2[i] == 32: s += 1 default: o += 1 } } fmt.Printf("字符串英文字符個數是: %d\n",e) fmt.Printf("字符串數字字符個數是: %d\n",d) fmt.Printf("字符串空格字符個數是: %d\n",s) fmt.Printf("字符串其它字符個數是: %d\n",o) } func main() { charactortype() }
方法二
經過regexp正則表達式匹配並統計spa
package main import ( "fmt" "regexp" ) // 練習四: 統計一個字符串的字母,數字,空格,其餘字符個數 func statisticalCharacterNumber(s string) { // 示例字符串 // var s = "MemTotal: 100111 KB" // 建立正則匹配字母、數字、空格 // \d 匹配數。 MustCompile必須 var rNum = regexp.MustCompile(`\d`) // [a-zA-Z] 匹配大小寫字母 var rCharacter = regexp.MustCompile("[a-zA-Z]") // 匹配空格 var rBlank = regexp.MustCompile(" ") // 定義其它字符變量 var specialcharacter int // 獲取數字的個數 num := len(rNum.FindAllStringSubmatch(s,-1)) // 獲取字母的個數 character := len(rCharacter.FindAllStringSubmatch(s,-1)) // 獲取空格的個數 blank := len(rBlank.FindAllStringSubmatch(s,-1)) fmt.Printf("數字個數%d\n",num) fmt.Printf("字母個數%d\n",character) fmt.Printf("空格個數%d\n",blank) //其它字符 specialcharacter = len(s) - num - character - blank fmt.Printf("其它字符個數%d\n",specialcharacter) fmt.Printf("總個數%d\n",len(s)) } func main() { statisticalCharacterNumber("MemTotal: 100111 KB") }