1
1
package Text
2
2
3
- // Returns all occurences of needle in haystack
3
+ // Returns all occurrences of needle in haystack
4
4
func findAll (haystack []rune , needle string ) []int {
5
-
6
5
needleAsRunes := []rune (needle )
7
6
lenNeedle := len (needleAsRunes )
8
7
9
8
if len (haystack ) == 0 || len (needle ) == 0 || lenNeedle > len (haystack ) {
10
9
return []int {}
11
10
}
12
11
13
- items := make ([]int , 0 , 8 )
14
-
15
- for i := 0 ; i < len (haystack ); i ++ {
16
- for j := 0 ; j < lenNeedle ; j ++ {
17
- if haystack [i + j ] != needleAsRunes [j ] {
18
- break
19
- }
12
+ var items []int
20
13
21
- if j == lenNeedle - 1 {
22
- items = append (items , i )
23
- }
14
+ limit := len (haystack ) - lenNeedle
15
+ for i := 0 ; i <= limit ; i ++ {
16
+ if matchAt (haystack , needleAsRunes , i ) {
17
+ items = append (items , i )
24
18
}
25
19
}
26
20
@@ -36,17 +30,10 @@ func findFirst(haystack []rune, needle string) int {
36
30
return - 1
37
31
}
38
32
39
- lenHaystack := len (haystack )
40
-
41
- for i := 0 ; i <= lenHaystack - lenNeedle ; i ++ {
42
- for j := 0 ; j < lenNeedle ; j ++ {
43
- if haystack [i + j ] != needleAsRunes [j ] {
44
- break
45
- }
46
-
47
- if j == lenNeedle - 1 {
48
- return i
49
- }
33
+ limit := len (haystack ) - lenNeedle
34
+ for i := 0 ; i <= limit ; i ++ {
35
+ if matchAt (haystack , needleAsRunes , i ) {
36
+ return i
50
37
}
51
38
}
52
39
@@ -62,19 +49,22 @@ func findLast(haystack []rune, needle string) int {
62
49
return - 1
63
50
}
64
51
65
- lenHaystack := len (haystack )
66
-
67
- for i := lenHaystack - lenNeedle ; i >= 0 ; i -- {
68
- for j := 0 ; j < lenNeedle ; j ++ {
69
- if haystack [i + j ] != needleAsRunes [j ] {
70
- break
71
- }
72
-
73
- if j == lenNeedle - 1 {
74
- return i
75
- }
52
+ limit := len (haystack ) - lenNeedle
53
+ for i := limit ; i >= 0 ; i -- {
54
+ if matchAt (haystack , needleAsRunes , i ) {
55
+ return i
76
56
}
77
57
}
78
58
79
59
return - 1
80
60
}
61
+
62
+ // Checks if the needle matches within the haystack starting at a given position.
63
+ func matchAt (haystack []rune , needle []rune , pos int ) bool {
64
+ for j := range needle {
65
+ if haystack [pos + j ] != needle [j ] {
66
+ return false
67
+ }
68
+ }
69
+ return true
70
+ }
0 commit comments