Go: Retrieve a string from between two characters or other strings

后端 未结 7 1679
有刺的猬
有刺的猬 2021-01-05 14:47

Let\'s say for example that I have one string, like this:

Hello World!

What Go code would be able to extract Hel

相关标签:
7条回答
  • 2021-01-05 15:38
    func findInString(str, start, end string) ([]byte, error) {
        var match []byte
        index := strings.Index(str, start)
    
        if index == -1 {
            return match, errors.New("Not found")
        }
    
        index += len(start)
    
        for {
            char := str[index]
    
            if strings.HasPrefix(str[index:index+len(match)], end) {
                break
            }
    
            match = append(match, char)
            index++
        }
    
        return match, nil
    }
    
    0 讨论(0)
提交回复
热议问题