string.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package utils
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strconv"
  6. )
  7. // HasPrefix 判断字符串是否以指定前缀开头
  8. func HasPrefix(s *string, prefix string) bool {
  9. pl := len(prefix)
  10. return len(*s) >= pl && (*s)[:pl] == prefix
  11. }
  12. // IsPrefix 检查字符串 s 是否以 prefix 开头,并返回一个新的字符串,
  13. // 如果 s 不以 prefix 开头,则在 s 前面添加 prefix。
  14. func IsPrefix(s, prefix string) string {
  15. if s == "" || prefix == "" {
  16. return s + prefix
  17. }
  18. if HasPrefix(&s, prefix) {
  19. return s
  20. }
  21. return prefix + s
  22. }
  23. // HasSuffix 判断字符串是否以指定后缀结尾
  24. func HasSuffix(s *string, suffix string) bool {
  25. if s == nil {
  26. return false
  27. }
  28. return len(*s) >= len(suffix) && (*s)[len(*s)-len(suffix):] == suffix
  29. }
  30. // IsSuffix 检查字符串 s 是否以 suffix 结尾,并返回一个新的字符串,
  31. // 如果 s 不以 suffix 结尾,则在 s 后面添加 suffix。
  32. func IsSuffix(s, suffix string) string {
  33. if s == "" || suffix == "" {
  34. return s + suffix
  35. }
  36. if HasSuffix(&s, suffix) {
  37. return s
  38. }
  39. return s + suffix
  40. }
  41. func ToString(i interface{}) (string, error) {
  42. value := reflect.ValueOf(i)
  43. switch value.Kind() {
  44. case reflect.String:
  45. return value.String(), nil
  46. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  47. return strconv.FormatInt(value.Int(), 10), nil
  48. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  49. return strconv.FormatUint(value.Uint(), 10), nil
  50. case reflect.Float32, reflect.Float64:
  51. return strconv.FormatFloat(value.Float(), 'g', -1, 64), nil
  52. case reflect.Bool:
  53. return strconv.FormatBool(value.Bool()), nil
  54. default:
  55. return "", fmt.Errorf("无法将 %s 类型转换为 string", value.Type())
  56. }
  57. }