You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.1 KiB

  1. /*
  2. * The MIT License (MIT)
  3. *
  4. * Copyright (c) 2015 Ian Coleman
  5. * Copyright (c) 2018 Ma_124, <github.com/Ma124>
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, Subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in all
  15. * copies or Substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. * SOFTWARE.
  24. */
  25. package strcase
  26. import (
  27. "strings"
  28. )
  29. // Converts a string to CamelCase
  30. func toCamelInitCase(s string, initCase bool) string {
  31. s = addWordBoundariesToNumbers(s)
  32. s = strings.Trim(s, " ")
  33. n := ""
  34. capNext := initCase
  35. for _, v := range s {
  36. if v >= 'A' && v <= 'Z' {
  37. n += string(v)
  38. }
  39. if v >= '0' && v <= '9' {
  40. n += string(v)
  41. }
  42. if v >= 'a' && v <= 'z' {
  43. if capNext {
  44. n += strings.ToUpper(string(v))
  45. } else {
  46. n += string(v)
  47. }
  48. }
  49. if v == '_' || v == ' ' || v == '-' {
  50. capNext = true
  51. } else {
  52. capNext = false
  53. }
  54. }
  55. return n
  56. }
  57. // ToCamel converts a string to CamelCase
  58. func ToCamel(s string) string {
  59. return toCamelInitCase(s, true)
  60. }
  61. // ToLowerCamel converts a string to lowerCamelCase
  62. func ToLowerCamel(s string) string {
  63. if s == "" {
  64. return s
  65. }
  66. if r := rune(s[0]); r >= 'A' && r <= 'Z' {
  67. s = strings.ToLower(string(r)) + s[1:]
  68. }
  69. return toCamelInitCase(s, false)
  70. }