首页 > 后端开发 > Golang > 正文

golang怎么查找字符串

下次还敢
发布: 2024-05-26 20:36:25
原创
387人浏览过
Go 提供了多种查找字符串的方法: 1. Index 函数查找子字符串的第一个出现位置,如果没有则返回 -1。 2. IndexByte 函数查找单个字符(字节)的第一个出现位置。 3. LastIndex 函数从字符串末尾开始查找子字符串的最后一个出现位置。 4. Contains 函数检查子字符串是否存在,存在返回 true,不存在返回 false。 5. HasPrefix 和 HasSuffix 函数检查字符串是否以子字符串开头或结尾,符合返回 true,否则返回 false。

golang怎么查找字符串

如何在 Go 中查找字符串

Go 提供了多种方法来查找字符串:

1. 使用 Index

Index 函数返回指定子字符串在字符串中的第一个出现位置,如果没有匹配项,则返回 -1。

立即学习go语言免费学习笔记(深入)”;

<code class="go">package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Hello, Go!"
    index := strings.Index(str, "Go")
    if index == -1 {
        fmt.Println("Not found")
    } else {
        fmt.Println("Found at index:", index)
    }
}</code>
登录后复制

2. 使用 IndexByte

IndexByte 函数类似于 Index,但它适用于单个字符(字节)。

阿里云-虚拟数字人
阿里云-虚拟数字人

阿里云-虚拟数字人是什么? ...

阿里云-虚拟数字人 2
查看详情 阿里云-虚拟数字人
<code class="go">package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Hello, Go!"
    index := strings.IndexByte(str, 'G')
    if index == -1 {
        fmt.Println("Not found")
    } else {
        fmt.Println("Found at index:", index)
    }
}</code>
登录后复制

3. 使用 LastIndex

LastIndex 函数与 Index 类似,但它从字符串的末尾开始搜索。

<code class="go">package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Hello, Go Go!"
    index := strings.LastIndex(str, "Go")
    if index == -1 {
        fmt.Println("Not found")
    } else {
        fmt.Println("Found at index:", index)
    }
}</code>
登录后复制

4. 使用 Contains

Contains 函数检查字符串中是否包含指定的子字符串,如果包含,则返回 true,否则返回 false。

<code class="go">package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Hello, Go!"
    contains := strings.Contains(str, "Go")
    if contains {
        fmt.Println("Yes, it contains 'Go'")
    } else {
        fmt.Println("No, it doesn't contain 'Go'")
    }
}</code>
登录后复制

5. 使用 HasPrefix 和 HasSuffix

HasPrefixHasSuffix 函数检查字符串是否以指定的子字符串开头或结尾,如果符合,则返回 true,否则返回 false。

<code class="go">package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Hello, Go!"
    hasPrefix := strings.HasPrefix(str, "Hello")
    hasSuffix := strings.HasSuffix(str, "Go!")
    if hasPrefix {
        fmt.Println("Yes, it starts with 'Hello'")
    } else {
        fmt.Println("No, it doesn't start with 'Hello'")
    }
    if hasSuffix {
        fmt.Println("Yes, it ends with 'Go!'")
    } else {
        fmt.Println("No, it doesn't end with 'Go!'")
    }
}</code>
登录后复制

以上就是golang怎么查找字符串的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号