Golang语言字符串处理函数包strings,字符串类型转换包strconv。
/**
* Golang语言字符串处理函数包strings,字符串类型转换包strconv
*/
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
str := "This is an example of a string"
fmt.Printf("Ture/False? Does the string "%s" have prefix %s?", str, "Th")
// 判断字符串的前缀
fmt.Printf("%tn", strings.HasPrefix(str, "Th"))
fmt.Printf("True/False? Does the string "%s" have suffix %s?", str, "ing")
// 判断字符串的后缀
fmt.Printf("%tn", strings.HasSuffix(str, "ing"))
fmt.Printf("True/False? Does the string "%s" have %s?", str, "xa")
// 判断字符串是否包含某字符
fmt.Printf("%tn", strings.Contains(str, "xa"))
// 判断指定字符在字符串第一次出现的位置
fmt.Printf("%dn", strings.Index(str, "s"))
// 判断指定字符在字符串最后一次出现的位置
fmt.Printf("%dn", strings.LastIndex(str, "s"))
// 将字符串中的前n个字符替换,并返回一个新字符串,如果n=-1则替换所有字符串中的字符
fmt.Printf("%sn", strings.Replace(str, "is", "at", 1))
// 统计指定字符在字符串中出现的次数
fmt.Printf("%dn", strings.Count(str, "s"))
// 将字符串重复n次,并返回新字符串
fmt.Printf("%sn", strings.Repeat(str, 2))
// 将字符串全部转换为小写字符
fmt.Printf("%sn", strings.ToLower(str))
// 将字符串全部转换为大写字符
fmt.Printf("%sn", strings.ToUpper(str))
// 去除字符串开头和结尾的空格
str1 := " This is an example of a string "
fmt.Printf("%sn", strings.TrimSpace(str1))
// 去除字符串开头和结尾的指定字符,只去除字符串开头或结尾的指定字符
str2 := "my name is frank, this pencil is my"
fmt.Printf("%sn", strings.Trim(str2, "my"))
fmt.Printf("%sn", strings.TrimLeft(str2, "my"))
fmt.Printf("%sn", strings.TrimRight(str2, "my"))
// 分割字符串,转换为一个slice
// 利用1个或多个空白字符来作为分隔符,将字符串分割成若干小块,并返回一个slice
// 如果字符串只包含空白字符串,则返回一个长度为0的slice
sli := strings.Fields(str)
for _, value := range sli {
fmt.Println(value)
}
str3 := "2019-05-07"
sli2 := strings.Split(str3, "-")
for _, value := range sli2 {
fmt.Println(value)
}
// 拼接slice元素成为一个字符串
fmt.Printf("%sn", strings.Join(sli2, "-"))
// 字符串类型转换
str4 := "123"
// 字符串类型转换为int
num, _ := strconv.Atoi(str4)
fmt.Printf("%dn", num)
// int转换为字符串类型
newStr4 := strconv.Itoa(num)
fmt.Printf("%sn", newStr4)
}
运行结果:
Ture/False? Does the string "This is an example of a string" have prefix Th?true
True/False? Does the string "This is an example of a string" have suffix ing?true
True/False? Does the string "This is an example of a string" have xa?true
3
24
That is an example of a string
3
This is an example of a stringThis is an example of a string
this is an example of a string
THIS IS AN EXAMPLE OF A STRING
This is an example of a string
name is frank, this pencil is
name is frank, this pencil is my
my name is frank, this pencil is
This
is
an
example
of
a
string
2019
05
07
2019-05-07
123
123