当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go基础编程实践(一)—— 操作字符串

Go基础编程实践(一)—— 操作字符串

2019年06月30日  | 移动技术网IT编程  | 我要评论

修剪空格

strings包中的trimspace函数用于去掉字符串首尾的空格。

package main

import (
    "fmt"
    "strings"
)

func main() {
    helloworld := "\t hello, world "
    trimhello := strings.trimspace(helloworld)

    fmt.printf("%d %s\n", len(helloworld), helloworld)
    fmt.printf("%d %s\n", len(trimhello), trimhello)

    // 15    hello, world 
    // 12 hello, world
}

提取子串

go字符串的底层是read-only[]byte,所以对切片的任何操作都可以应用到字符串。

package main

import "fmt"

func main() {
    helloworld := "hello, world and water"
    cuthello := helloworld[:12]
    fmt.println(cuthello)
    // hello, world
}

替换子串

strings包的replace函数可以对字符串中的子串进行替换。

package main

import (
    "fmt"
    "strings"
)

func main() {
    helloworld := "hello, world. i'm still fine."
    replacehello := strings.replace(helloworld, "fine", "ok", 1)
    fmt.println(replacehello)
    // hello, world. i'm still ok.
}
// 注:replace函数的最后一个参数表示替换子串的个数,为负则全部替换。

转义字符

字符串中需要出现的特殊字符要用转义字符\转义先,例如\t需要写成\\t

package main

import "fmt"

func main() {
    helloworld := "hello, \t world."
    escapehello := "hello, \\t world."
    fmt.println(helloworld)
    fmt.println(escapehello)
    // hello,    world.
    // hello, \t world.
}

大写字符

strings包的title函数用于将每个单词的首字母大写,toupper函数则将单词的每个字母都大写。

package main

import (
    "fmt"
    "strings"
)

func main() {
    helloworld := "hello, world. i'm still fine."
    titlehello :=strings.title(helloworld)
    upperhello := strings.toupper(helloworld)
    fmt.println(titlehello)
    fmt.println(upperhello)
    // hello, world. i'm still fine.
    // hello, world. i'm still fine.
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网