douhui2307 2015-08-18 20:14
浏览 53
已采纳

删除字符串中的所有空格

What is the fastest way to strip all whitespace from some arbitrary string in Go.

I am chaining two function from the string package:

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

Anyone have a better way to do this?

  • 写回答

3条回答 默认 最新

  • dsf8897 2015-08-18 20:18
    关注

    Here is some benchmarks on a few different methods for stripping all whitespace characters from a string: (source data):

    BenchmarkSpaceMap-8                     2000       1100084 ns/op      221187 B/op          2 allocs/op
    BenchmarkSpaceFieldsJoin-8              1000       2235073 ns/op     2299520 B/op         20 allocs/op
    BenchmarkSpaceStringsBuilder-8          2000        932298 ns/op      122880 B/op          1 allocs/op
    
    • SpaceMap: uses strings.Map; gradually increases the amount of allocated space as more non-whitespace characters are encountered
    • SpaceFieldsJoin: strings.Fields and strings.Join; generates a lot of intermediate data
    • SpaceStringsBuilder uses strings.Builder; performs a single allocation, but may grossly overallocate if the source string is mainly whitespace.
    package main_test
    
    import (
        "strings"
        "unicode"
        "testing"
    )
    
    func SpaceMap(str string) string {
        return strings.Map(func(r rune) rune {
            if unicode.IsSpace(r) {
                return -1
            }
            return r
        }, str)
    }
    
    func SpaceFieldsJoin(str string) string {
        return strings.Join(strings.Fields(str), "")
    }
    
    func SpaceStringsBuilder(str string) string {
        var b strings.Builder
        b.Grow(len(str))
        for _, ch := range str {
            if !unicode.IsSpace(ch) {
                b.WriteRune(ch)
            }
        }
        return b.String()
    }
    
    func BenchmarkSpaceMap(b *testing.B) {
        for n := 0; n < b.N; n++ {
            SpaceMap(data)
        }
    }
    
    func BenchmarkSpaceFieldsJoin(b *testing.B) {
        for n := 0; n < b.N; n++ {
            SpaceFieldsJoin(data)
        }
    }
    
    func BenchmarkSpaceStringsBuilder(b *testing.B) {
        for n := 0; n < b.N; n++ {
            SpaceStringsBuilder(data)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起