File: stringsx.go

package info (click to toggle)
golang-github-icza-gox 0.0~git20210726.cd40a3f-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 332 kB
  • sloc: makefile: 2
file content (63 lines) | stat: -rw-r--r-- 1,402 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package stringsx

import (
	"strings"
	"unicode"
	"unicode/utf8"
)

// Clean removes non-graphic characters from the given string.
// Removable characters are the ones for which unicode.IsGraphic() returns false.
//
// For details, see https://stackoverflow.com/a/58994297/1705598
func Clean(s string) string {
	return strings.Map(func(r rune) rune {
		if unicode.IsGraphic(r) {
			return r
		}
		return -1
	}, s)
}

// LimitRunes returns a slice of s that contains at most the given number of runes.
// If n is 0 or negative, the empty string is returned.
// If s has less runes than n, s is returned.
//
// Each byte of invalid UTF-8 sequences count as one when counting the limit, e.g.
//   LimitRunes("\xff\xffab", 3) // returns "\xff\xffa"
func LimitRunes(s string, n int) string {
	if n <= 0 || s == "" {
		return ""
	}

	for i := range s {
		n--
		if n == -1 {
			return s[:i]
		}
	}
	// s has n or less runes
	return s
}

// SplitQuotes splits the given string by sep.
// If sep appears inside quotes, it is skipped.
// Quotes are not removed from the parts.
func SplitQuotes(s string, sep, quote rune) (parts []string) {
	sepLen := utf8.RuneLen(sep)

	start, inQuotes := 0, false

	for i, r := range s {
		if r == sep && !inQuotes {
			parts = append(parts, s[start:i])
			start = i + sepLen
			continue
		}
		if r == quote {
			inQuotes = !inQuotes
		}
	}

	return append(parts, s[start:])
}