Go basic string operations

Strings Strings in
Go language appear as native data types. Using strings is like using other native data types. The internal implementation of Go language strings is encoded in utf-8, and the value of the string is in the double quotation mark "". Content, you can directly add
the escape of non-ASCII character strings in the source code of the Go language.
\r Carriage return\n Line feed\t Tab character\' Single quote\" Double quotes\ Backslash
Multi-line string
Go language When you want to specify a multi-line string in, you need to use backticks ``

package main

import "fmt"
func main() {
    
    
    s := `
        君不见
        黄河之水天上来
        奔流到海不复回
    `
    fmt.Print(s)
}

Common operations on strings

package main

import (
    "fmt"
    "strings"
)
func main() {
    
    
    s := "sdfasdfa"
    //求长度
    fmt.Println(len(s)) //8
    //拼接字符串
    ss := s + "sdfasdf"
    fmt.Println(ss)
    fmt.Sprintln(s, ss) //sdfasdfasdfasdf
    //以什么什么字符分割,
    arr := strings.Split(ss, "a")
    fmt.Printf("%v\n", arr) //[sdf sdf sdf sdf]
    //判断是否包含
    b := strings.Contains(ss, "sdf")
    fmt.Printf("%T--%v\n", b, b) //bool--true
    //判断以什么什么开头
    b1 := strings.HasPrefix(ss, "sdf")
    fmt.Printf("%T--%v\n", b1, b1) //bool--true
    //判断以什么什么结尾
    b2 := strings.HasSuffix(ss, "sdf")
    fmt.Printf("%T--%v\n", b2, b2) //bool--true
    //子串出现的位置
    i := strings.Index(ss, "a")
    fmt.Printf("%T--%v\n", i, i) //int--3
    //join操作
    s1 := strings.Join(arr, "00")
    fmt.Printf("%T--%v\n", s1, s1) //string--sdf00sdf00sdf00sdf
}

Byte and rune types
Each element of a string is called a character, and the character is obtained by traversing or obtaining a single string element.
There are two kinds of characters in Go language,

package main

import (
    "fmt"
)
func main() {
    
    
s := "sdfasdfa" 
//遍历字符串
    for _, sss := range s {
    
    
        fmt.Print(string(sss))
    }
}

uint8 type, also called byte represents a character of ASCII
int32 type, also called rune represents a UTF-8 character.
When you need to deal with Chinese, Japanese and other composite characters, you need rune type, rune type is actually int32
Go uses special Type processing Unicode makes it more convenient for text processing based on Unicode. You can use byte for default string processing. Both performance and scalability are taken care of.
Modifying the string
To modify the string, you need to convert it to []rune or [ ]byte, change to string after completion, no matter what kind of conversion, reallocate the memory and copy the byte array

package main

import (
    "fmt"
)
func main() {
    
    
    s := "sdfasdfa"
    ss := []rune(s)
    ss[4] = '董'
    fmt.Println(string(ss))
}

Guess you like

Origin blog.csdn.net/weixin_44865158/article/details/114290868