|
4 | 4 | */
|
5 | 5 | package collection
|
6 | 6 |
|
7 |
| -import "strings" |
| 7 | +import ( |
| 8 | + "strings" |
| 9 | + "unicode" |
| 10 | +) |
8 | 11 |
|
9 |
| -// ParseListWithCleanup splits a string into a list like strings.Split but also removes any whitespace surrounding the different items |
10 |
| -// for example, |
11 |
| -// ParseListWithCleanup("a, b , c", ",") returns []{"a","b","c"} |
12 |
| -func ParseListWithCleanup(input string, sep string) (newS []string) { |
| 12 | +func lineIsOnlyWhitespace(line string) bool { |
| 13 | + for _, c := range line { |
| 14 | + if !unicode.IsSpace(c) { |
| 15 | + return false |
| 16 | + } |
| 17 | + } |
| 18 | + return true |
| 19 | +} |
| 20 | + |
| 21 | +func parseListWithCleanup(input string, sep string, keepBlankLines bool) (newS []string) { |
13 | 22 | if len(input) == 0 {
|
14 | 23 | newS = []string{} // initialisation of empty arrays in function returns []string(nil) instead of []string{}
|
15 | 24 | return
|
16 | 25 | }
|
17 | 26 | split := strings.Split(input, sep)
|
18 | 27 | for _, s := range split {
|
19 | 28 | tempString := strings.TrimSpace(s)
|
20 |
| - if tempString != "" { |
| 29 | + if tempString != "" || (keepBlankLines && lineIsOnlyWhitespace(s)) { |
21 | 30 | newS = append(newS, tempString)
|
22 | 31 | }
|
23 | 32 | }
|
24 | 33 | return
|
25 | 34 | }
|
26 | 35 |
|
| 36 | +// ParseListWithCleanup splits a string into a list like strings.Split but also removes any whitespace surrounding the different items |
| 37 | +// for example, |
| 38 | +// ParseListWithCleanup("a, b , c", ",") returns []{"a","b","c"} |
| 39 | +func ParseListWithCleanup(input string, sep string) (newS []string) { |
| 40 | + return parseListWithCleanup(input, sep, false) |
| 41 | +} |
| 42 | + |
| 43 | +// ParseListWithCleanupKeepBlankLines splits a string into a list like strings.Split but also removes any whitespace surrounding the different items |
| 44 | +// unless the entire item is whitespace in which case it is converted to an empty string. For example, |
| 45 | +// ParseListWithCleanupKeepBlankLines("a, b , c", ",") returns []{"a","b","c"} |
| 46 | +// ParseListWithCleanupKeepBlankLines("a, b , , c", ",") returns []{"a","b", "", "c"} |
| 47 | +func ParseListWithCleanupKeepBlankLines(input string, sep string) (newS []string) { |
| 48 | + return parseListWithCleanup(input, sep, true) |
| 49 | +} |
| 50 | + |
27 | 51 | // ParseCommaSeparatedList returns the list of string separated by a comma
|
28 | 52 | func ParseCommaSeparatedList(input string) []string {
|
29 | 53 | return ParseListWithCleanup(input, ",")
|
|
0 commit comments