-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringf.go
74 lines (69 loc) · 1.41 KB
/
stringf.go
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
64
65
66
67
68
69
70
71
72
73
74
package stringf
const ESCCHAR = '{';
const ESCCHAREND = '}';
func isAlphabet(r rune) bool {
if (r < 'a' || 'z' < r) && (r < 'A' || 'Z' < r) && ( r < '0' || '9' < r) && r != '_' && r != ESCCHAREND {
return false
}
return true
}
func copyr(s string) []rune {
rs := make([]rune, 0, len(s))
for _, r := range s {
rs = append(rs, r)
}
return rs
}
// Format format s using map m
// Keys of map m can be anything but must not contains spaces
func Format(us string, m map[string]string) string {
s := copyr(us)
i := 0
output := ""
for i < len(s) {
if s[i] == ESCCHAR {
j := i + 1
for j < len(s) && s[j] == ESCCHAR {
j++
if (j - i) % 2 == 0 {
output += string(ESCCHAR)
}
}
if (j - i) % 2 != 0 {
param := ""
for j < len(s) && s[j] != ESCCHAREND && isAlphabet(s[j]) {
param += string(s[j])
j++
}
if len(param) > 0 {
if !isAlphabet(s[j]) {
output = output + string(ESCCHAR) + param[0:len(param)-1]
j--
} else {
v, ok := m[param]
if !ok { // no key ->
output = output + string(ESCCHAR) + param
if j >= len(s) {
} else if s[j] == ESCCHAREND {
output += string(ESCCHAREND)
}
} else {
output += v
}
}
}
if j == len(s) {
return output
} else if s[j] == ESCCHAREND {
j++
}
}
i = j
}
if i < len(s) {
output += string(s[i])
}
i++
}
return output
}