Commit a8f0d5a63ebe9483bd8fec8865f2e8a9da90de4c
1 parent
84543a02b2
Exists in
master
SplitText
Showing
1 changed file
with
48 additions
and
1 deletions
Show diff stats
string_util.go
... | ... | @@ -4,6 +4,7 @@ import ( |
4 | 4 | "fmt" |
5 | 5 | "strconv" |
6 | 6 | "strings" |
7 | + "unicode" | |
7 | 8 | ) |
8 | 9 | |
9 | 10 | const sanitisationPatern = "\"';&*<>=\\`:" |
... | ... | @@ -100,6 +101,53 @@ func StringAt(s string, index int) string { |
100 | 101 | return string(s[index]) |
101 | 102 | } |
102 | 103 | |
104 | +// SplitText ... | |
105 | +func SplitText(s string, maxLen int) (lines []string) { | |
106 | + runes := []rune(s) | |
107 | + | |
108 | + i, start, sep, l := 0, 0, 0, 0 | |
109 | + for i = 0; i < len(runes); i++ { | |
110 | + c := runes[i] | |
111 | + | |
112 | + if unicode.IsSpace(c) { | |
113 | + sep = i | |
114 | + } | |
115 | + | |
116 | + if c == '\n' { | |
117 | + if start != sep { | |
118 | + lines = append(lines, string(runes[start:sep])) | |
119 | + } | |
120 | + start = i | |
121 | + sep = i | |
122 | + l = 0 | |
123 | + } else if l >= maxLen { | |
124 | + if start != sep { | |
125 | + lines = append(lines, string(runes[start:sep])) | |
126 | + sep = i | |
127 | + start = i - 1 | |
128 | + l = 0 | |
129 | + } | |
130 | + } else { | |
131 | + l++ | |
132 | + } | |
133 | + } | |
134 | + if start != i-1 { | |
135 | + lines = append(lines, string(runes[start:i-1])) | |
136 | + } | |
137 | + | |
138 | + return lines | |
139 | +} | |
140 | + | |
141 | +const threeDots = "\u2056\u2056\u2056" | |
142 | + | |
143 | +func LimitTextWithThreeDots(txt string, maxLen int) string { | |
144 | + if len(txt) <= maxLen { | |
145 | + return txt | |
146 | + } | |
147 | + | |
148 | + return txt[:maxLen] + threeDots | |
149 | +} | |
150 | + | |
103 | 151 | // SplitStringAtWholeWords ... |
104 | 152 | func SplitStringAtWholeWords(s string, maxLen int) (res []string) { |
105 | 153 | parts := strings.Split(s, " ") |
... | ... | @@ -123,4 +171,3 @@ func SplitStringAtWholeWords(s string, maxLen int) (res []string) { |
123 | 171 | |
124 | 172 | return res |
125 | 173 | } |
126 | - | ... | ... |