1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
package main
import "fmt"
func main() {
// 定义字符串变量
str1 := "Hello, World!"
fmt.Println("str1:", str1)
// 字符串拼接
str2 := "Hello, " + "Golang!"
fmt.Println("str2:", str2)
// 获取字符串长度
length := len(str1)
fmt.Println("Length of str1:", length)
// 字符串索引访问
char := str1[0]
fmt.Println("First character of str1:", char)
// 遍历字符串
for i := 0; i < len(str1); i++ {
fmt.Println("Character at index", i, ":", str1[i])
}
// 使用反引号创建原始字符串
str3 := `This is a raw string \n`
fmt.Println("str3:", str3)
// 字符串切片
slice := str1[7:12]
fmt.Println("Slice of str1:", slice)
// 字符串替换
str4 := "Hello, Golang!"
newStr := replaceString(str4, "Golang", "World")
fmt.Println("New string:", newStr)
}
func replaceString(s, old, new string) string {
return s[:5] + new + s[12:]
}
|