从字符串中去除所有空格

从 Go 中的任意字符串中去除所有空格的最快方法是什么。

我从 string 包中链接了两个函数:

response = strings.Join(strings.Fields(response),"")

任何人都有更好的方法来做到这一点?


倚天杖
浏览 202回答 3
3回答

汪汪一只猫

以下是一些用于从字符串中去除所有空白字符的不同方法的基准测试:(源数据):BenchmarkSpaceMap-8 2000 1100084 ns/op 221187 B/op 2 allocs/opBenchmarkSpaceFieldsJoin-8 1000 2235073 ns/op 2299520 B/op 20 allocs/opBenchmarkSpaceStringsBuilder-8 2000 932298 ns/op 122880 B/op 1 allocs/opSpaceMap: 使用strings.Map; 随着遇到更多非空白字符,逐渐增加分配的空间量SpaceFieldsJoin:strings.Fields和strings.Join; 产生大量中间数据SpaceStringsBuilder用途strings.Builder; 执行单个分配,但如果源字符串主要是空格,则可能会严重过度分配。package main_testimport (&nbsp; &nbsp; "strings"&nbsp; &nbsp; "unicode"&nbsp; &nbsp; "testing")func SpaceMap(str string) string {&nbsp; &nbsp; return strings.Map(func(r rune) rune {&nbsp; &nbsp; &nbsp; &nbsp; if unicode.IsSpace(r) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return -1&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return r&nbsp; &nbsp; }, str)}func SpaceFieldsJoin(str string) string {&nbsp; &nbsp; return strings.Join(strings.Fields(str), "")}func SpaceStringsBuilder(str string) string {&nbsp; &nbsp; var b strings.Builder&nbsp; &nbsp; b.Grow(len(str))&nbsp; &nbsp; for _, ch := range str {&nbsp; &nbsp; &nbsp; &nbsp; if !unicode.IsSpace(ch) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.WriteRune(ch)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return b.String()}func BenchmarkSpaceMap(b *testing.B) {&nbsp; &nbsp; for n := 0; n < b.N; n++ {&nbsp; &nbsp; &nbsp; &nbsp; SpaceMap(data)&nbsp; &nbsp; }}func BenchmarkSpaceFieldsJoin(b *testing.B) {&nbsp; &nbsp; for n := 0; n < b.N; n++ {&nbsp; &nbsp; &nbsp; &nbsp; SpaceFieldsJoin(data)&nbsp; &nbsp; }}func BenchmarkSpaceStringsBuilder(b *testing.B) {&nbsp; &nbsp; for n := 0; n < b.N; n++ {&nbsp; &nbsp; &nbsp; &nbsp; SpaceStringsBuilder(data)&nbsp; &nbsp; }}

米脂

我发现最简单的方法是使用strings.ReplaceAll像这样:randomString := "&nbsp; hello&nbsp; &nbsp; &nbsp; this is a test"fmt.Println(strings.ReplaceAll(randomString, " ", ""))>hellothisisatest
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go