-
Notifications
You must be signed in to change notification settings - Fork 0
/
searchablestring.go
83 lines (69 loc) · 2 KB
/
searchablestring.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
75
76
77
78
79
80
81
82
83
package generics
import (
"fmt"
)
// function designed to append a string to the string.
func (ss SearchableString) Append(target rune) (newslice SearchableString) {
return SearchableString(fmt.Sprintf("%s%c", ss.String(), target))
}
// function designed to append a string to the string.
func (ss SearchableString) AppendString(target string) (newslice SearchableString) {
return SearchableString(fmt.Sprintf("%s%s", ss.String(), target))
}
// function designed to reset the object to
// the state it is when initialized. this will
// set strings to "".
func (ss SearchableString) Clear() SearchableString {
return ""
}
// function designed to search through a searchablestring
// and determine if the target rune (char) is in it.
func (ss SearchableString) In(target rune) (err error) {
var current rune
var found bool
// loop over each character in the string and compare
// it to the target char. if a match is found, set the
// found flag and break the loop.
for _, current = range ss {
if current == target {
found = true
break
}
}
// if the char was not found within the string, return
// an error stating as much.
if !found {
return fmt.Errorf("%c not found in %s", target, ss)
}
return nil
}
// function designed to find the index of a given char.
func (ss SearchableString) IndexOf(target rune) (idx int, err error) {
// make sure the target is in the string before
// looping through to grab the index.
if err = ss.In(target); err != nil {
return -1, err
}
var currentIdx int
var currentChr rune
for currentIdx, currentChr = range ss {
if currentChr == target {
idx = currentIdx
break
}
}
return idx, nil
}
// function designed to return the length of the object.
// this will loop throught the object and iterate a counter,
// returning the number of elements present in the string
// representation of the object.
func (ss SearchableString) Length() (count int) {
for range ss {
count++
}
return count
}
func (ss SearchableString) String() string {
return string(ss)
}