Go语言中字符串操作常用函数介绍

OctopusLian · 2019-04-21 22:40:52 · 2388 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    
这是一个创建于 2019-04-21 22:40:52 的文章,其中的信息可能已经有所发展或是发生改变。

  • 操作
    //"helloogo"中是否包含"hello"
    fmt.Println(strings.Contains("helloogo", "hello"))
    fmt.Println(strings.Contains("helloogo", "goe"))

    //Join组合
    s := []string{"abc", "hello", "mike", "go"}
    buf := strings.Join(s, "_")
    fmt.Println("buf = ", buf)

    //Index 查找子串所在位置
    fmt.Println(strings.Index("abcdhello", "hello"))
    fmt.Println(strings.Index("abcdhello", "go"))

    //Repeat 重复打印
    buf = strings.Repeat("go", 3)
    fmt.Println("buf = ", buf)

    //Split 以指定的分隔符对字符串进行拆分
    buf = "hello&abc&go&mike&you"
    s2 := strings.Split(buf, "&")
    fmt.Println("s2 = ", s2)

    //Trim 去掉两头的字符
    buf = strings.Trim("      are you ok    ", " ")
    fmt.Println("buf = ", buf)

    //Fields 去掉空格,把元素放入切片中
    s3 := strings.Fields("    are you ok?    ")
    for i, data := range s3 {
        fmt.Println(i, ", ", data)
    }
  • 输出
true
false
buf =  abc_hello_mike_go
4
-1
buf =  gogogo
s2 =  [hello abc go mike you]
buf =  are you ok
0 ,  are
1 ,  you
2 ,  ok?

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2388 次点击  
加入收藏 微博
被以下专栏收入,发现更多相似内容
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传