str.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package text
  5. // StrCount returns the number of runes in the specified string
  6. func StrCount(s string) int {
  7. count := 0
  8. for range s {
  9. count++
  10. }
  11. return count
  12. }
  13. // StrFind returns the start and length of the rune at the
  14. // specified position in the string
  15. func StrFind(s string, pos int) (start, length int) {
  16. count := 0
  17. for index := range s {
  18. if count == pos {
  19. start = index
  20. count++
  21. continue
  22. }
  23. if count == pos+1 {
  24. length = index - start
  25. break
  26. }
  27. count++
  28. }
  29. if length == 0 {
  30. length = len(s) - start
  31. }
  32. return start, length
  33. }
  34. // StrRemove removes the rune from the specified string and position
  35. func StrRemove(s string, col int) string {
  36. start, length := StrFind(s, col)
  37. return s[:start] + s[start+length:]
  38. }
  39. // StrInsert inserts a string at the specified character position
  40. func StrInsert(s, data string, col int) string {
  41. start, _ := StrFind(s, col)
  42. return s[:start] + data + s[start:]
  43. }
  44. // StrPrefix returns the prefix of the specified string up to
  45. // the specified character position
  46. func StrPrefix(text string, pos int) string {
  47. count := 0
  48. for index := range text {
  49. if count == pos {
  50. return text[:index]
  51. }
  52. count++
  53. }
  54. return text
  55. }