generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unpack.go
63 lines (48 loc) · 1.01 KB
/
unpack.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
package hw02unpackstring
import (
"errors"
"strconv"
"strings"
"unicode"
)
var ErrInvalidString = errors.New("invalid string")
func Unpack(str string) (string, error) {
sr := []rune(str)
var backslash bool
var sb strings.Builder
for i, char := range sr {
if unicode.IsDigit(char) && i == 0 {
return "", ErrInvalidString
}
if unicode.IsDigit(char) && unicode.IsDigit(sr[i-1]) && sr[i-2] != '\\' {
return "", ErrInvalidString
}
if char == '\\' && !backslash {
backslash = true
continue
}
if backslash && unicode.IsLetter(char) {
return "", ErrInvalidString
}
if backslash {
sb.WriteRune(char)
backslash = false
continue
}
if unicode.IsDigit(char) {
n, _ := strconv.Atoi(string(char))
if n == 0 {
tr := []rune(sb.String())
tr = tr[:len(tr)-1]
sb.Reset()
sb.WriteString(string(tr))
continue
}
repeater := strings.Repeat(string(sr[i-1]), n-1)
sb.WriteString(repeater)
continue
}
sb.WriteRune(char)
}
return sb.String(), nil
}