main.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package yu_path
  2. // Format
  3. //
  4. // @Description: 格式化文件或目录名称,去除所有转义符及不合规符号
  5. func Format(s string) string {
  6. j_buf := make([]byte, 0, len(s))
  7. j_space := true
  8. for j_i := 0; j_i < len(s); j_i++ {
  9. switch s[j_i] {
  10. case 0, '\\', '/', '<', '>', ':', '"', '|', '?', '*':
  11. case ' ':
  12. if j_space {
  13. continue
  14. }
  15. j_buf = append(j_buf, s[j_i])
  16. default:
  17. j_space = false
  18. j_buf = append(j_buf, s[j_i])
  19. }
  20. }
  21. j_eof := len(j_buf)
  22. for j_eof > 0 {
  23. j_eof--
  24. if j_buf[j_eof] != ' ' && j_buf[j_eof] != '.' {
  25. break
  26. }
  27. }
  28. if j_buf[j_eof] == ' ' || j_buf[j_eof] == '.' {
  29. return ""
  30. }
  31. j_eof++
  32. return string(j_buf[:j_eof])
  33. }
  34. // Join
  35. //
  36. // @Description: 组合路径
  37. func Join(s ...string) string {
  38. if len(s) == 0 {
  39. return ""
  40. }
  41. if len(s) == 1 {
  42. return s[0]
  43. }
  44. j_buf := make([]byte, 0, len(s)*128)
  45. j_buf = append(j_buf, s[0]...)
  46. for j_i := 1; j_i < len(s); j_i++ {
  47. j_buf = append(j_buf, '\\')
  48. j_buf = append(j_buf, s[j_i]...)
  49. }
  50. return string(j_buf)
  51. }
  52. // JoinFormat
  53. //
  54. // @Description: 组合路径并去除路径中的转义符,如:["\\","\/","//","../","..\"]
  55. func JoinFormat(s ...string) string {
  56. if len(s) == 0 {
  57. return ""
  58. }
  59. if len(s) == 1 {
  60. return Format(s[0])
  61. }
  62. j_buf := make([]byte, 0, len(s)*128)
  63. j_buf = append(j_buf, Format(s[0])...)
  64. for j_i := 1; j_i < len(s); j_i++ {
  65. j_buf = append(j_buf, '\\')
  66. j_buf = append(j_buf, Format(s[j_i])...)
  67. }
  68. return string(j_buf)
  69. }