string_utils.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package string
  2. import (
  3. "strconv"
  4. "strings"
  5. )
  6. func IsEmptyOrNil(s string) bool {
  7. return &s == nil || len(s) == 0
  8. }
  9. func IsBlank(s string) bool {
  10. return strings.TrimSpace(s) == ""
  11. }
  12. func IsNotBlank(s string) bool {
  13. return !IsBlank(s)
  14. }
  15. func StringToIntSlice(strSlice []string) ([]int, error) {
  16. var intSlice []int
  17. for _, str := range strSlice {
  18. num, err := strconv.Atoi(str)
  19. if err != nil {
  20. return nil, err
  21. }
  22. intSlice = append(intSlice, num)
  23. }
  24. return intSlice, nil
  25. }
  26. func StringsToJSON(str string) string {
  27. rs := []rune(str)
  28. jsons := ""
  29. for _, r := range rs {
  30. rint := int(r)
  31. if rint < 128 {
  32. jsons += string(r)
  33. } else {
  34. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  35. }
  36. }
  37. return jsons
  38. }
  39. func IntToStringSlice(intSlice []int) []string {
  40. var strSlice []string
  41. for _, num := range intSlice {
  42. strSlice = append(strSlice, strconv.Itoa(num))
  43. }
  44. return strSlice
  45. }
  46. func RemoveEmptyStrings(slice []string) []string {
  47. var filteredSlice []string
  48. for _, s := range slice {
  49. if s != "" {
  50. filteredSlice = append(filteredSlice, s)
  51. }
  52. }
  53. return filteredSlice
  54. }
  55. func UniqueItems(items []string) []string {
  56. seen := make(map[string]bool)
  57. result := []string{}
  58. for _, item := range items {
  59. if seen[item] {
  60. continue
  61. }
  62. seen[item] = true
  63. result = append(result, item)
  64. }
  65. return result
  66. }