utils_str.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2019 gf Author(https://github.com/gogf/gf). 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 utils
  7. import (
  8. "strings"
  9. )
  10. // IsLetterUpper checks whether the given byte b is in upper case.
  11. func IsLetterUpper(b byte) bool {
  12. if b >= byte('A') && b <= byte('Z') {
  13. return true
  14. }
  15. return false
  16. }
  17. // IsLetterLower checks whether the given byte b is in lower case.
  18. func IsLetterLower(b byte) bool {
  19. if b >= byte('a') && b <= byte('z') {
  20. return true
  21. }
  22. return false
  23. }
  24. // IsLetter checks whether the given byte b is a letter.
  25. func IsLetter(b byte) bool {
  26. return IsLetterUpper(b) || IsLetterLower(b)
  27. }
  28. // IsNumeric checks whether the given string s is numeric.
  29. // Note that float string like "123.456" is also numeric.
  30. func IsNumeric(s string) bool {
  31. length := len(s)
  32. if length == 0 {
  33. return false
  34. }
  35. for i := 0; i < len(s); i++ {
  36. if s[i] == '-' && i == 0 {
  37. continue
  38. }
  39. if s[i] == '.' {
  40. if i > 0 && i < len(s)-1 {
  41. continue
  42. } else {
  43. return false
  44. }
  45. }
  46. if s[i] < '0' || s[i] > '9' {
  47. return false
  48. }
  49. }
  50. return true
  51. }
  52. // UcFirst returns a copy of the string s with the first letter mapped to its upper case.
  53. func UcFirst(s string) string {
  54. if len(s) == 0 {
  55. return s
  56. }
  57. if IsLetterLower(s[0]) {
  58. return string(s[0]-32) + s[1:]
  59. }
  60. return s
  61. }
  62. // ReplaceByMap returns a copy of <origin>,
  63. // which is replaced by a map in unordered way, case-sensitively.
  64. func ReplaceByMap(origin string, replaces map[string]string) string {
  65. for k, v := range replaces {
  66. origin = strings.Replace(origin, k, v, -1)
  67. }
  68. return origin
  69. }
  70. // RemoveSymbols removes all symbols from string and lefts only numbers and letters.
  71. func RemoveSymbols(s string) string {
  72. var b []byte
  73. for _, c := range s {
  74. if (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') {
  75. b = append(b, byte(c))
  76. }
  77. }
  78. return string(b)
  79. }
  80. // EqualFoldWithoutChars checks string <s1> and <s2> equal case-insensitively,
  81. // with/without chars '-'/'_'/'.'/' '.
  82. func EqualFoldWithoutChars(s1, s2 string) bool {
  83. return strings.EqualFold(RemoveSymbols(s1), RemoveSymbols(s2))
  84. }