Golang语言包-字符串处理strings和字符串类型转换strconv

frankphper · · 1022 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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("%t\n", strings.HasPrefix(str, "Th")) fmt.Printf("True/False? Does the string \"%s\" have suffix %s?", str, "ing") // 判断字符串的后缀 fmt.Printf("%t\n", strings.HasSuffix(str, "ing")) fmt.Printf("True/False? Does the string \"%s\" have %s?", str, "xa") // 判断字符串是否包含某字符 fmt.Printf("%t\n", strings.Contains(str, "xa")) // 判断指定字符在字符串第一次出现的位置 fmt.Printf("%d\n", strings.Index(str, "s")) // 判断指定字符在字符串最后一次出现的位置 fmt.Printf("%d\n", strings.LastIndex(str, "s")) // 将字符串中的前n个字符替换,并返回一个新字符串,如果n=-1则替换所有字符串中的字符 fmt.Printf("%s\n", strings.Replace(str, "is", "at", 1)) // 统计指定字符在字符串中出现的次数 fmt.Printf("%d\n", strings.Count(str, "s")) // 将字符串重复n次,并返回新字符串 fmt.Printf("%s\n", strings.Repeat(str, 2)) // 将字符串全部转换为小写字符 fmt.Printf("%s\n", strings.ToLower(str)) // 将字符串全部转换为大写字符 fmt.Printf("%s\n", strings.ToUpper(str)) // 去除字符串开头和结尾的空格 str1 := " This is an example of a string " fmt.Printf("%s\n", strings.TrimSpace(str1)) // 去除字符串开头和结尾的指定字符,只去除字符串开头或结尾的指定字符 str2 := "my name is frank, this pencil is my" fmt.Printf("%s\n", strings.Trim(str2, "my")) fmt.Printf("%s\n", strings.TrimLeft(str2, "my")) fmt.Printf("%s\n", 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("%s\n", strings.Join(sli2, "-")) // 字符串类型转换 str4 := "123" // 字符串类型转换为int num, _ := strconv.Atoi(str4) fmt.Printf("%d\n", num) // int转换为字符串类型 newStr4 := strconv.Itoa(num) fmt.Printf("%s\n", 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 ```

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

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

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