gstr_count.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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/gogf/gf.
  6. package gstr
  7. import (
  8. "bytes"
  9. "strings"
  10. "unicode"
  11. )
  12. // Count counts the number of `substr` appears in `s`.
  13. // It returns 0 if no `substr` found in `s`.
  14. func Count(s, substr string) int {
  15. return strings.Count(s, substr)
  16. }
  17. // CountI counts the number of `substr` appears in `s`, case-insensitively.
  18. // It returns 0 if no `substr` found in `s`.
  19. func CountI(s, substr string) int {
  20. return strings.Count(ToLower(s), ToLower(substr))
  21. }
  22. // CountWords returns information about words' count used in a string.
  23. // It considers parameter `str` as unicode string.
  24. func CountWords(str string) map[string]int {
  25. m := make(map[string]int)
  26. buffer := bytes.NewBuffer(nil)
  27. for _, r := range []rune(str) {
  28. if unicode.IsSpace(r) {
  29. if buffer.Len() > 0 {
  30. m[buffer.String()]++
  31. buffer.Reset()
  32. }
  33. } else {
  34. buffer.WriteRune(r)
  35. }
  36. }
  37. if buffer.Len() > 0 {
  38. m[buffer.String()]++
  39. }
  40. return m
  41. }
  42. // CountChars returns information about chars' count used in a string.
  43. // It considers parameter `str` as unicode string.
  44. func CountChars(str string, noSpace ...bool) map[string]int {
  45. m := make(map[string]int)
  46. countSpace := true
  47. if len(noSpace) > 0 && noSpace[0] {
  48. countSpace = false
  49. }
  50. for _, r := range []rune(str) {
  51. if !countSpace && unicode.IsSpace(r) {
  52. continue
  53. }
  54. m[string(r)]++
  55. }
  56. return m
  57. }