Introduction to string type in go language

In Go, String is an immutable type and cannot be modified.

In the Go language, strings are composed of Unicode characters, and each character can be represented by one or more bytes. We use double quotes or backticks to define strings, and strings defined with backticks will not escape any content (for example, they \nwill not be escaped when included in text)

s1 := "hello, world\n"
fmt.Print(s1)

// 使用反引号定义的原生字符串
s2 := `hello, world\n`
fmt.Print(s2)

// 使用反斜杠进行转义
s3 := "C:\\Windows\\System32\\"
fmt.Print(s3)

Common string operations are:

  1. Get length: built-in functionlen()
  2. concatenation: plus operator +or fmt.Sprintf()formatting
  3. Interception: slice operation
  4. Traversal: for loop and range keyword
  5. Comparison: comparison operators ==, !=, <, <=, >, >=

The following is a sample code that demonstrates how to define and use the string type in Go language:

var str1 string = "Hello"
var str2 string = "world"
// 获取长度
fmt.Println(len(str1))
// 拼接
var str3 string = str1 + " " + str2
// 截取
fmt.Printf("str3[1:4]: %s\n", str3[1:4])
// 遍历
for index, char := range str3 {
    
    
 fmt.Printf("str3[%d]: %c\n", index, char)
}
// 比较
if str1 == "Hello" {
    
    
 fmt.Println("str1 equals Hello")
}

String concatenation performance optimization:

In both Go and Java, strings are treated as constants in memory. Therefore, concatenating strings continuously using the "+" sign will incur a lot of performance overhead. For this, we have some strategies for optimizing string concatenation:

  1. Type of use strings.Builder : This method is suitable for situations where you have not prepared all the strings that need to be concatenated in advance.

  2. Using strings.Join()the function: This method is suitable for situations where you have prepared all the strings that need to be concatenated, and allows us to insert separators in the concatenated strings, which is required in some cases. But this approach consumes a lot of memory.

// 输出:11-22
join := strings.Join( []string{
    
    "11", "22"}, "-" )

Here is an example application of both methods:

// strings.Builder
start := time.Now()
var name strings.Builder
for i := 0; i < 100000; i++ {
    
    
	name.WriteString(strconv.Itoa(i))
}
fmt.Println(time.Since(start))
// strings.Join()
start := time.Now()
var strs []string
for i := 0; i < 100000; i++ {
    
    
	strs = append(strs, strconv.Itoa(i))
}
name := strings.Join(strs, "")
fmt.Println(time.Since(start))
fmt.Println(len(name))

In some experiments we got the following results:

  1. Native form: 1.3 seconds average
  2. strings.Builder: Average 2.3 ms
  3. strings.Join(): Average 4.8 ms

Guess you like

Origin blog.csdn.net/qq_35760825/article/details/131750487