string.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package util
  2. import (
  3. "strconv"
  4. "strings"
  5. )
  6. // StrSliToSQLVarchars convert string slice to varchar in sql syntax
  7. // eg: ["default", "deleted", "modified"] -> " 'default', 'deleted', 'modified' "
  8. // so that we can used it in 'SELECT * ... WHERE xxx IN ('default', 'deleted', 'modified')'
  9. func StrSliToSQLVarchars(s []string) string {
  10. sli := make([]string, len(s))
  11. for i, ss := range s {
  12. sli[i] = "'" + ss + "'"
  13. }
  14. return strings.Join(sli, ",")
  15. }
  16. // StrToIntSli convert string to int slice, eg: "1,2,3" -> [1,2,3]
  17. func StrToIntSli(s string, delimiter string) ([]int64, error) {
  18. var result []int64
  19. sli := strings.Split(s, delimiter)
  20. for _, intStr := range sli {
  21. i, err := strconv.ParseInt(intStr, 10, 64)
  22. if err != nil {
  23. return nil, err
  24. }
  25. result = append(result, i)
  26. }
  27. return result, nil
  28. }
  29. // IntSliToSQLVarchars convert int slice to string, eg: [1,2,3] -> "1,2,3"
  30. func IntSliToSQLVarchars(ints []int64) string {
  31. return intSliToStr(ints, ",")
  32. }
  33. func intSliToStr(ints []int64, delimiter string) string {
  34. sli := make([]string, len(ints))
  35. for i, ii := range ints {
  36. sli[i] = strconv.FormatInt(ii, 10)
  37. }
  38. return strings.Join(sli, delimiter)
  39. }
  40. // SameChar check if string consists of same characters
  41. func SameChar(content string) bool {
  42. content = strings.ToLower(content)
  43. first := content[0]
  44. for _, s := range content {
  45. if s != rune(first) {
  46. return false
  47. }
  48. }
  49. return true
  50. }
  51. // StripPrefix remove prefix from string if exists
  52. func StripPrefix(s string, prefix string, suffix string) string {
  53. if strings.HasPrefix(s, prefix) {
  54. i := strings.Index(s, suffix)
  55. return s[i+1:]
  56. }
  57. return s
  58. }