52

Is there a StartsWith(str1, str2 string) function that can check if str1 is a prefix of str2 in Go language?

I want a function similar to the Java's startsWith().

Jeremy Caney
  • 4,585
  • 13
  • 32
  • 54
Ammar
  • 3,640
  • 6
  • 25
  • 27
  • 1
    possible duplicate of [No startswith,endswith functions in Go?](http://stackoverflow.com/questions/13244048/no-startswith-endswith-functions-in-go) – LaGrandMere Mar 04 '14 at 14:52

1 Answers1

93

The strings package has what you are looking for. Specifically the HasPrefix function: http://golang.org/pkg/strings/#HasPrefix

Example:

fmt.Println(strings.HasPrefix("my string", "prefix"))  // false
fmt.Println(strings.HasPrefix("my string", "my"))      // true

That package is full of a lot of different string helper functions you should check out.

Community
  • 1
  • 1
Jeremy Wall
  • 20,762
  • 4
  • 50
  • 72