string.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package util
  2. import "strings"
  3. // Title returns a string value with s[0] which has been convert into upper case that
  4. // there are not empty input text
  5. func Title(s string) string {
  6. if len(s) == 0 {
  7. return s
  8. }
  9. return strings.ToUpper(s[:1]) + s[1:]
  10. }
  11. // Untitle returns a string value with s[0] which has been convert into lower case that
  12. // there are not empty input text
  13. func Untitle(s string) string {
  14. if len(s) == 0 {
  15. return s
  16. }
  17. return strings.ToLower(s[:1]) + s[1:]
  18. }
  19. // Index returns the index where the item equal,it will return -1 if mismatched
  20. func Index(slice []string, item string) int {
  21. for i := range slice {
  22. if slice[i] == item {
  23. return i
  24. }
  25. }
  26. return -1
  27. }
  28. // SafeString converts the input string into a safe naming style in golang
  29. func SafeString(in string) string {
  30. if len(in) == 0 {
  31. return in
  32. }
  33. data := strings.Map(func(r rune) rune {
  34. if isSafeRune(r) {
  35. return r
  36. }
  37. return '_'
  38. }, in)
  39. headRune := rune(data[0])
  40. if isNumber(headRune) {
  41. return "_" + data
  42. }
  43. return data
  44. }
  45. func isSafeRune(r rune) bool {
  46. return isLetter(r) || isNumber(r) || r == '_'
  47. }
  48. func isLetter(r rune) bool {
  49. return 'A' <= r && r <= 'z'
  50. }
  51. func isNumber(r rune) bool {
  52. return '0' <= r && r <= '9'
  53. }