No startswith,endswith functions in Go?

StringGo

String Problem Overview


Just curious to findout: why aren't there standard functions like startswith, endswith, etc as part of the standard libraries in the Go programming language?

String Solutions


Solution 1 - String

The strings package contains HasPrefix and HasSuffix.

import "strings"

startsWith := strings.HasPrefix("prefix", "pre") // true
endsWith := strings.HasSuffix("suffix", "fix") // true

play.golang.org

Solution 2 - String

If you are working with bytes, you can use these functions from the bytes package:

package main

import (
   "bytes"
   "fmt"
)

func main() {
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
}

It will be less costly than converting to string first. Useful if you are reading in from an HTTP request, or reading from a local file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSahasView Question on Stackoverflow
Solution 1 - StringKyle FinleyView Answer on Stackoverflow
Solution 2 - StringZomboView Answer on Stackoverflow