1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-08 14:42:27 +08:00

feat: add FindAllOccurrences

This commit is contained in:
dudaodong
2025-01-10 14:03:45 +08:00
parent a0d97cf38e
commit 7653afa919
5 changed files with 119 additions and 7 deletions

View File

@@ -738,14 +738,14 @@ func RegexMatchAllGroups(pattern, str string) [][]string {
// ExtractContent extracts the content between the start and end strings in the source string.
// Play: https://go.dev/play/p/Ay9UIk7Rum9
func ExtractContent(s, start, end string) []string {
func ExtractContent(str, start, end string) []string {
result := []string{}
for {
if _, after, ok := strings.Cut(s, start); ok {
if _, after, ok := strings.Cut(str, start); ok {
if before, _, ok := strings.Cut(after, end); ok {
result = append(result, before)
s = after
str = after
} else {
break
}
@@ -756,3 +756,20 @@ func ExtractContent(s, start, end string) []string {
return result
}
// FindAllOccurrences returns the positions of all occurrences of a substring in a string.
// Play: todo
func FindAllOccurrences(str, substr string) []int {
var positions []int
for i := 0; i < len(str); {
index := strings.Index(str[i:], substr)
if index == -1 {
break
}
positions = append(positions, i+index)
i += index + 1
}
return positions
}