开始以(str string)开头

huangapple go评论76阅读模式
英文:

Go StartsWith(str string)

问题

在Go语言中是否有一个StartsWith(str1, str2 string)函数,可以检查str1是否是str2的前缀?

我想要一个类似于Java的startsWith()的函数。

英文:

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

答案1

得分: 211

strings包中有你要找的功能。具体来说,有HasPrefix函数:http://golang.org/pkg/strings/#HasPrefix

示例:

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

该包中还有许多不同的字符串辅助函数,你应该去查看一下。

英文:

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.

答案2

得分: 9

例如

如果你想检查一个字符串是否以点号开头

package main

import "strings"

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

终端:

$ true
英文:

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

huangapple
  • 本文由 发表于 2012年10月1日 11:50:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/12667327.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定