Method One
Judging and counting by ASCII code table
package mainimport "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()}
Method Two
Match and count by regexp regular expression
package Mainimport ("FMT" "regexp")//Practice Four: Statistics A string of letters, numbers, spaces, number of other characters func Statisticalcharacternu Mber (s string) {//Sample string//var s = "memtotal:100111 KB"//create regular match letters, numbers, spaces//\d match number. Mustcompile must be var rnum = RegExp. Mustcompile (' \d ')//[a-za-z] matches the uppercase and lowercase letters var rcharacter = RegExp. Mustcompile ("[a-za-z]")//Match space var rblank = RegExp. Mustcompile ("")//define other character variables var specialcharacter int//get number num: = Len (Rnum.findallstringsubmatch (s,-1)) Get the number of letters character: = Len (Rcharacter.findallstringsubmatch (s,-1))//Get the number of spaces blank: = Len (rblank.findall Stringsubmatch (s,-1)) fmt. Printf ("Number%d\n", num) fmt. Printf ("Number of letters%d\n", character) fmt. Printf ("Number of spaces%d\n", blank)//other characters specialcharacter = Len (s)-Num-character-blank FMT. Printf ("Number of other characters%d\n", Specialcharacter) fmt. Printf ("Total number%d\n", Len (s))}func main () {Statisticalcharacternumber ("memtotal:100111 KB")}