方法一
通过ASCII码表判断并统计
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()}
方法二
通过regexp正则表达式匹配并统计
package mainimport ( "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")}