go标准库strings — 字符串操作
Go语言的strings包提供了一些用于操作字符串的函数。这些函数主要包括字符串的比较、查找、替换、分割、前后缀和大小写转换等操作。
以下是一些使用Go标准库strings包的常见操作的示例代码:
- 字符串比较:
package main
import (
"fmt"
"strings"
)
func main() {
str1 := "Hello, World!"
str2 := "Hello, Go!"
if strings.Compare(str1, str2) == 0 {
fmt.Println("str1 and str2 are equal")
} else {
fmt.Println("str1 and str2 are not equal")
}
}
- 字符串查找:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, World!"
substr := "World"
if strings.Contains(str, substr) {
fmt.Println("Found substring:", substr)
} else {
fmt.Println("Substring not found:", substr)
}
}
- 字符串替换:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, World!"
oldStr := "World"
newStr := "Go"
str = strings.Replace(str, oldStr, newStr, -1)
fmt.Println("Replaced string:", str)
}
- 字符串分割:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, World!"
delimiter := ","
splitted := strings.Split(str, delimiter)
fmt.Println("Splitted string:", splitted)
}
- 字符串前后缀检查:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, World!"
if strings.HasPrefix(str, "Hello") {
fmt.Println("String has prefix 'Hello'")
}
if strings.HasSuffix(str, "World!") {
fmt.Println("String has suffix 'World!'")
}
}
- 字符串大小写转换:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, World!"
lowerStr := strings.ToLower(str)
fmt.Println("Lowercase string:", lowerStr)
upperStr := strings.ToUpper(str)
fmt.Println("Uppercase string:", upperStr)
}
- 字符串去空格:
package main
import (
"fmt"
"strings"
)
func main() {
str := " Hello, World! "
trimmed := strings.TrimSpace(str)
fmt.Println("Trimmed string:", trimmed)
}
- 字符串其他操作:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, World!"
// 获取字符串长度
length := len(str)
fmt.Println("Length of string:", length)
// 获取字符串中某个字符的位置
char := "o"
index := strings.Index(str, char)
fmt.Println("Index of character '" + char + "':", index)
评论已关闭