1. Statistics of string length: len(str)
The len(str) function is used to count the length of strings by bytes. This function is a built-in function and does not need to be imported. It can be used directly. The example is as follows:
//统计字符串的长度,按字节进行统计:
str := "golang你好"//在golang中, 汉字是utf-8字符集,一个汉字3个字节
fmt.Print1n(len(str))//12字节
2. String traversal
(1) Utilization method 1: for-range key value loop
//对字符串进行遍历:
//方式1:利用键值循环: for-range
for i,value := range str {
fmt.Printf("索引为: %d, 具体的值为: %c \n", i, value)
}
The results are as follows:
(2) Utilization method 2: r:=[]rune(str)
//方式2:利用r:=[ ]rune(str)
r:=[]rune(str)
fori:=0;i<len(r);i++{
fmt. Printf("%c \n" ,r[i])
}
The result is as follows:
3. Convert string to integer: Atoi
n, err := strconv.Atoi("66")
4. Convert integer to string: Itoa
str = strconv.Itoa(6887)
5. Find whether the substring is in the specified string: Contains
strings.Contains("javaandgolang", "go")
6. Count how many specified substrings a string has: Count
//统计一个字符串有几个指定的子串:
count := strings.Count("golangandjavaga", ga")
fmt.Println(count) //2
7. Case-insensitive string comparison: EqualFold
//不区分大小写的字符串比较:
flag := strings.EqualFold("hello","HELLO")
fmt.Println(flag)//true
//区分大小写进行字符串比较:
fmt.Println("hello"=="Hello")//false
8. Return the index value of the first occurrence of the substring in the string. If not, return -1: lndex
//返回子串在字符串第一次出现的索引值,如果没有返回-1 :
fmt.Println(strings.Index("golangandjavaga" ,”ga0"))
9. String replacement: Replace
//strings.Replace("goandjavagogo", "go", "golang", n)
//n可以指定你希望替换几个,如果n=-1表示全部替换,替换两个n就是2
func main(){
//字符串的替换:
str1 := strings.Replace("goandjavagogo","go","golang", -1)
str2 := strings.Replace("goandjavagogo", "go","golang",2)
fmt.Print1n(str1)
fmt .Print1n(str2)
}
The result is as follows:
10. Split a string into a string array according to a specified character as the split identifier: Split
//按照指定的某个字符,为分割标识,将一个学符串拆分成字符串数组:
arr := strings.Split(" go-python-java", "-")
fmt.Print1n(arr)
11. Convert string letters to uppercase and lowercase
//将字符串的字母进行 大小写的转换:
fmt.Println(strings. ToLower("Go"))
fmt.Println(strings. ToUpper("go"))
12. Remove the spaces on the left and right sides of the string
//将字符串左右两边的空格去掉:
fmt.Println(strings.TrimSpace(" go and java "))
13. Remove the specified characters on the left and right sides of the string
//将字符串左右两边指定的字符去掉:
fmt.Println(strings.Trim("~golang~","~"))
14. Remove the specified characters on the left side of the string
strings.TrimLeft("~golang~", "~")
15. Remove the specified characters on the right side of the string
strings.TrimRight("~golang~", "~")
16. Determine whether a string begins with the specified string
strings.HasPrefix("http://java.sun.com/jsp/jstl/fmt", "http")
17. Determine whether the string ends with the specified string
strings.HasSuffix("demo.png", ".png")