Repository navigation
Expand file tree
/
Copy pathgstr_pos.go
More file actions
106 lines (96 loc) · 2.97 KB
/
Copy pathgstr_pos.go
File metadata and controls
106 lines (96 loc) · 2.97 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gstr
import "strings"
// Find the position of the first occurrence of a substring in a string.
//
// 返回 needle 在 haystack 中首次出现的数字位置,找不到返回-1。
func Pos(haystack, needle string, startOffset...int) int {
length := len(haystack)
offset := 0
if len(startOffset) > 0 {
offset = startOffset[0]
}
if length == 0 || offset > length || -offset > length {
return -1
}
if offset < 0 {
offset += length
}
pos := strings.Index(haystack[offset : ], needle)
if pos == -1 {
return -1
}
return pos + offset
}
// Find the position of the first occurrence of a case-insensitive substring in a string.
//
// 返回在字符串 haystack 中 needle 首次出现的数字位置(不区分大小写),找不到返回-1。
func PosI(haystack, needle string, startOffset...int) int {
length := len(haystack)
offset := 0
if len(startOffset) > 0 {
offset = startOffset[0]
}
if length == 0 || offset > length || -offset > length {
return -1
}
haystack = haystack[offset : ]
if offset < 0 {
offset += length
}
pos := strings.Index(strings.ToLower(haystack), strings.ToLower(needle))
if pos == -1 {
return -1
}
return pos + offset
}
// Find the position of the last occurrence of a substring in a string.
//
// 查找指定字符串在目标字符串中最后一次出现的位置,找不到返回-1。
func PosR(haystack, needle string, startOffset...int) int {
offset := 0
if len(startOffset) > 0 {
offset = startOffset[0]
}
pos, length := 0, len(haystack)
if length == 0 || offset > length || -offset > length {
return -1
}
if offset < 0 {
haystack = haystack[ : offset + length + 1]
} else {
haystack = haystack[offset : ]
}
pos = strings.LastIndex(haystack, needle)
if offset > 0 && pos != -1 {
pos += offset
}
return pos
}
// Find the position of the last occurrence of a case-insensitive substring in a string.
//
// 以不区分大小写的方式查找指定字符串在目标字符串中最后一次出现的位置,找不到返回-1。
func PosRI(haystack, needle string, startOffset...int) int {
offset := 0
if len(startOffset) > 0 {
offset = startOffset[0]
}
pos, length := 0, len(haystack)
if length == 0 || offset > length || -offset > length {
return -1
}
if offset < 0 {
haystack = haystack[:offset+length+1]
3683
div>
} else {
haystack = haystack[offset:]
}
pos = strings.LastIndex(strings.ToLower(haystack), strings.ToLower(needle))
if offset > 0 && pos != -1 {
pos += offset
}
return pos
}