方法一
通過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()}
方法二
通過regexpRegex匹配並統計
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")}