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. }
如对本文有疑问, 点击进行留言回复!!
VSCode1.4 搭建Golang的开发调试环境(遇到很多问题)
网友评论