SoFunction
Updated on 2025-03-05

Summary of common operations of GO language strings

Introduction to strings

A string is a sequence of characters connected by fixed-length characters. A string in the GO language is connected by a single byte, and its string bytes are encoded by UTF-8 to represent unicode text.

Due to the uncertainty of the byte length of this encoding, in GO language, strings will occupy 1 to 4 bytes as needed, which is different from other programming languages ​​(such as c++ python java). For example, Java strings always occupy 2 bytes. GO does this not only reduces the memory and hard disk usage, but also does not require other languages ​​to code UTF-8 like that.

Strings in GO are the same as strings in Java, and their values ​​are immutable (if they need to be modified after creation, they will only point the pointer to a new string). When a string exists in the code, the compiler will mark it as read-only data SRODATA

Common methods

Chinese string intercept

In GO, we can directly intercept strings through slices, but when the intercepted string is in Chinese, you should pay attention. In GO, English occupies one byte, and Chinese occupies 3 bytes. When we directly intercept with slices, we may cut the Chinese encoding in half, and the result is that the last word is garbled.

Here it is recommended to use a rune array to intercept the string, and then convert it to a string after intercepting it. What is intercepted through rune is not bytes, and each of the array stores this word (English letters, Chinese characters)

Examples are as follows:

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    // Declare a string    str := "This is a string, how to test go"

    // string length    ((str))
    // Byte length    (len(str))

    // This intercept is bytes    str1 := str[0:9]
    (str1)
    // One Chinese occupies 3 bytes. When 10 bytes are intercepted, the last Chinese character will be garbled.    str2 := str[0:10]
    (str2)

    // Convert the string to a rune array, then intercept and then return to the string    strRune := []rune(str)
    (len(strRune))
    // Note that this is not bytes, but 4 words    (string(strRune[0:4]))
}

//Output//17
//43
//This is a//This is a//17
//This is a string

Invert string

Here we still use the rune array used above. First convert it to the rune array type, reverse it, and then turn it back to the characters. Example

package main

import "fmt"

func main() {
    a := "123345asdfg"

    reverseStr := reverseString(a)
    (reverseStr)
}

func reverseString(a string) string {
    b := []rune(a)

    for i := 0; i < len(b)/2; i++ {
        // Note: You can't write like the following        //b[i] = b[len(b)-i-1]
        //b[len(b)-i-1] = b[i]

        // It can be understood that taking out both first and then assigning values ​​at the same time. It has to be said that it is still very simple, otherwise a third-party variable is needed to complete the interchange.        b[i], b[len(b)-i-1] = b[len(b)-i-1], b[i]
    }

    return string(b)
}

// gfdsa543321

String case operations

This is very simple. Just call the two methods provided in the strings package

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Hello World"

    // All letters are converted to capital    upper := (str)
    (upper)
    // All letters are converted to lowercase    lower := (str)
    (lower)
}

Remove the first space of the string

You can use the method TrimSpace() under the strings package, or use the Trim() method, which can delete continuous characters in a string, and it is of course possible to delete spaces.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := " GO is very useful "

    // Delete continuous characters    str1 := (str, " ")
    // Delete the first space    str2 := (str)

    (str)
    (str2)
    (str1)
}

Merge strings

join() is used to splice string slices into strings. The first parameter passes character slices, and the second is a connector. The following example is the space connection used.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := []string{"I", "Love", "GO"}
    res := (str, " ")
    (res)
}

Split string

The strings package provides four functions: Split(), SplitN, SplitAfter, and SplitAfterN() to handle regular split strings

func Splic(s,sep string) []string

where s is a regular-divided string and sep is a separator

func SplicN(s,sep string,n int) []string

Where s is a regular-divided string, sep is a separator, n is the number of slices to control, if it is -1, there is no limit.

func SplicAfter(s,sep string) []string

The function is the same as above but the splitter will be retained

func Splic(s,sep string) []string

The function is the same as above but the splitter will be retained

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "I_Love_Golang_web"

    split1 := (str, "_")
    split2 := (str, "_", 3)
    split3 := (str, "_")
    split4 := (str, "_", 2)

    for i := range split1 {
        (split1[i])
    }
    // I
    // Love
    // Golang
    // web

    for i := range split2 {
        (split2[i])
    }
    // I
    // Love
    // Golang_web

    for i := range split3 {
        (split3[i])
    }
    // I_
    // Love_
    // Golang_
    // web

    for i := range split4 {
        (split4[i])
    }
    // I_
    // Love_Golang_web
}

This is the end of this article about the commonly used operations of GO language strings. For more information about commonly used operations of GO strings, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!