146

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
  • 7,102
  • 69
  • 48
  • 77
Ammar
  • 5,070
  • 8
  • 28
  • 27
  • 3
    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

2 Answers2

214

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
  • 23,907
  • 5
  • 55
  • 73
10

For Example

If you want to check if a string starts with a dot

package main

import "strings"

func main() {
   str := ".com"
   fmt.Println(strings.HasPrefix(str, "."))
}

Terminal:

$ true
jarv
  • 5,338
  • 24
  • 26
gitaoh
  • 191
  • 2
  • 4