github.com/zhongdalu/gf@v1.0.0/g/text/gstr/gstr_pos.go (about) 1 // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 package gstr 8 9 import "strings" 10 11 // Pos returns the position of the first occurrence of <needle> 12 // in <haystack> from <startOffset>, case-sensitively. 13 // It returns -1, if not found. 14 func Pos(haystack, needle string, startOffset ...int) int { 15 length := len(haystack) 16 offset := 0 17 if len(startOffset) > 0 { 18 offset = startOffset[0] 19 } 20 if length == 0 || offset > length || -offset > length { 21 return -1 22 } 23 24 if offset < 0 { 25 offset += length 26 } 27 pos := strings.Index(haystack[offset:], needle) 28 if pos == -1 { 29 return -1 30 } 31 return pos + offset 32 } 33 34 // PosI returns the position of the first occurrence of <needle> 35 // in <haystack> from <startOffset>, case-insensitively. 36 // It returns -1, if not found. 37 func PosI(haystack, needle string, startOffset ...int) int { 38 length := len(haystack) 39 offset := 0 40 if len(startOffset) > 0 { 41 offset = startOffset[0] 42 } 43 if length == 0 || offset > length || -offset > length { 44 return -1 45 } 46 47 if offset < 0 { 48 offset += length 49 } 50 pos := strings.Index(strings.ToLower(haystack[offset:]), strings.ToLower(needle)) 51 if pos == -1 { 52 return -1 53 } 54 return pos + offset 55 } 56 57 // PosR returns the position of the last occurrence of <needle> 58 // in <haystack> from <startOffset>, case-sensitively. 59 // It returns -1, if not found. 60 func PosR(haystack, needle string, startOffset ...int) int { 61 offset := 0 62 if len(startOffset) > 0 { 63 offset = startOffset[0] 64 } 65 pos, length := 0, len(haystack) 66 if length == 0 || offset > length || -offset > length { 67 return -1 68 } 69 70 if offset < 0 { 71 haystack = haystack[:offset+length+1] 72 } else { 73 haystack = haystack[offset:] 74 } 75 pos = strings.LastIndex(haystack, needle) 76 if offset > 0 && pos != -1 { 77 pos += offset 78 } 79 return pos 80 } 81 82 // PosRI returns the position of the last occurrence of <needle> 83 // in <haystack> from <startOffset>, case-insensitively. 84 // It returns -1, if not found. 85 func PosRI(haystack, needle string, startOffset ...int) int { 86 offset := 0 87 if len(startOffset) > 0 { 88 offset = startOffset[0] 89 } 90 pos, length := 0, len(haystack) 91 if length == 0 || offset > length || -offset > length { 92 return -1 93 } 94 95 if offset < 0 { 96 haystack = haystack[:offset+length+1] 97 } else { 98 haystack = haystack[offset:] 99 } 100 pos = strings.LastIndex(strings.ToLower(haystack), strings.ToLower(needle)) 101 if offset > 0 && pos != -1 { 102 pos += offset 103 } 104 return pos 105 }