github.com/wangyougui/gf/v2@v2.6.5/text/gstr/gstr_count.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package gstr 8 9 import ( 10 "bytes" 11 "strings" 12 "unicode" 13 ) 14 15 // Count counts the number of `substr` appears in `s`. 16 // It returns 0 if no `substr` found in `s`. 17 func Count(s, substr string) int { 18 return strings.Count(s, substr) 19 } 20 21 // CountI counts the number of `substr` appears in `s`, case-insensitively. 22 // It returns 0 if no `substr` found in `s`. 23 func CountI(s, substr string) int { 24 return strings.Count(ToLower(s), ToLower(substr)) 25 } 26 27 // CountWords returns information about words' count used in a string. 28 // It considers parameter `str` as unicode string. 29 func CountWords(str string) map[string]int { 30 m := make(map[string]int) 31 buffer := bytes.NewBuffer(nil) 32 for _, r := range []rune(str) { 33 if unicode.IsSpace(r) { 34 if buffer.Len() > 0 { 35 m[buffer.String()]++ 36 buffer.Reset() 37 } 38 } else { 39 buffer.WriteRune(r) 40 } 41 } 42 if buffer.Len() > 0 { 43 m[buffer.String()]++ 44 } 45 return m 46 } 47 48 // CountChars returns information about chars' count used in a string. 49 // It considers parameter `str` as unicode string. 50 func CountChars(str string, noSpace ...bool) map[string]int { 51 m := make(map[string]int) 52 countSpace := true 53 if len(noSpace) > 0 && noSpace[0] { 54 countSpace = false 55 } 56 for _, r := range []rune(str) { 57 if !countSpace && unicode.IsSpace(r) { 58 continue 59 } 60 m[string(r)]++ 61 } 62 return m 63 }