Go StartsWith(str string)
Asked Answered
S

2

165

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().

Sonata answered 1/10, 2012 at 3:50 Comment(1)
possible duplicate of No startswith,endswith functions in Go?Underplay
L
238

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.

Lighterman answered 1/10, 2012 at 3:59 Comment(0)
C
15

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
Credo answered 3/6, 2021 at 12:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.