Golang counts the number of letters, spaces, numbers, and other characters

Source: Internet
Author: User

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")}  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.