Maison > développement back-end > Golang > le corps du texte

Utilisez la fonction strings.HasPrefix dans Golang pour déterminer si une chaîne commence par un certain préfixe

王林
Libérer: 2023-11-18 12:18:41
original
1518 Les gens l'ont consulté

Utilisez la fonction strings.HasPrefix dans Golang pour déterminer si une chaîne commence par un certain préfixe

使用 golang 中的 strings.HasPrefix 函数判断字符串是否以某个前缀开头

在 golang 中,strings.HasPrefix 函数可以帮助我们判断一个字符串是否以指定的前缀开头。我在工作中经常使用该函数来判断文件路径是否满足要求。下面是该函数的具体用法及代码示例。

函数介绍

函数名:HasPrefix
函数作用:判断字符串s是否以prefix开头
函数参数:s string - 要判断的字符串;prefix string - 前缀字符串
函数返回值:bool - 字符串s是否以prefix开头

函数代码示例

下面是使用该函数的示例代码:

package main

import (

"fmt"
"strings"
Copier après la connexion

)

func main(){

str1 := "/usr/local/go/bin/go"
str2 := "/usr/local/go/src"
api1 := "/api/v1/user"
api2 := "/api/v2/user"

// 判断str1是否以指定的前缀"/usr"开头
if strings.HasPrefix(str1, "/usr"){
    fmt.Printf("str1以/usr开头
Copier après la connexion

")

} else {
    fmt.Printf("str1不以/usr开头
Copier après la connexion

")

}

// 判断str2是否以指定的前缀"/usr"开头
if strings.HasPrefix(str2, "/usr"){
    fmt.Printf("str2以/usr开头
Copier après la connexion

")

} else {
    fmt.Printf("str2不以/usr开头
Copier après la connexion

")

}

// 判断api1是否以指定的前缀"/api/v1"开头
if strings.HasPrefix(api1, "/api/v1"){
    fmt.Printf("api1以/api/v1开头
Copier après la connexion

")

} else {
    fmt.Printf("api1不以/api/v1开头
Copier après la connexion

")

}

// 判断api2是否以指定的前缀"/api/v1"开头
if strings.HasPrefix(api2, "/api/v1"){
    fmt.Printf("api2以/api/v1开头
Copier après la connexion

")

} else {
    fmt.Printf("api2不以/api/v1开头
Copier après la connexion

")

}
Copier après la connexion

}

输出结果:

str1以/usr开头
str2以/usr开头
api1以/api/v1开头
api2不以/api/v1开头

从输出结果可以看出,strings.HasPrefix 函数可以很方便地判断一个字符串是否以指定的前缀开头。在实际工作中,我们可以根据业务需要来灵活使用该函数,从而提升代码的可读性和执行效率。

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!