Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go StartsWith(str string)

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

like image 574
Ammar Avatar asked Oct 01 '12 03:10

Ammar


People also ask

How to check prefix of a string in golang?

In Golang strings, you can check whether the string begins with the specified prefix or not with the help of HasPrefix() function. This function returns true if the given string starts with the specified prefix and return false if the given string does not start with the specified prefix.

How do you find the length of a string in Golang?

How to find the length of the string?: In Golang string, you can find the length of the string using two functions one is len() and another one is RuneCountInString(). The RuneCountInString() function is provided by UTF-8 package, this function returns the total number of rune presents in the string.


2 Answers

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.

like image 164
Jeremy Wall Avatar answered Sep 21 '22 06:09

Jeremy Wall


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 
like image 41
gitaoh Avatar answered Sep 23 '22 06:09

gitaoh