dongtaogu8510 2018-10-30 16:38
浏览 203
已采纳

检查字符串仅包含ASCII字符

Does Go have any method or there is a suggestion how to check if a string contains only ASCII characters? What is the right way to do it?

From my research, one of the solution is to check whatever there is any char greater than 127.

func isASCII(s string) bool {
    for _, c := range s {
        if c > unicode.MaxASCII {
            return false
        }
    }

    return true
}
  • 写回答

2条回答 默认 最新

  • dongye1912 2018-10-30 17:29
    关注

    In Go, we care about performance, Therefore, we would benchmark your code:

    func isASCII(s string) bool {
        for _, c := range s {
            if c > unicode.MaxASCII {
                return false
            }
        }
        return true
    }
    
    BenchmarkRange-4    20000000    82.0 ns/op
    

    A faster (better, more idiomatic) version, which avoids unnecessary rune conversions:

    func isASCII(s string) bool {
        for i := 0; i < len(s); i++ {
            if s[i] > unicode.MaxASCII {
                return false
            }
        }
        return true
    }
    
    BenchmarkIndex-4    30000000    55.4 ns/op
    

    ascii_test.go:

    package main
    
    import (
        "testing"
        "unicode"
    )
    
    func isASCIIRange(s string) bool {
        for _, c := range s {
            if c > unicode.MaxASCII {
                return false
            }
        }
        return true
    }
    
    func BenchmarkRange(b *testing.B) {
        str := ascii()
        b.ResetTimer()
        for N := 0; N < b.N; N++ {
            is := isASCIIRange(str)
            if !is {
                b.Fatal("notASCII")
            }
        }
    }
    
    func isASCIIIndex(s string) bool {
        for i := 0; i < len(s); i++ {
            if s[i] > unicode.MaxASCII {
                return false
            }
        }
        return true
    }
    
    func BenchmarkIndex(b *testing.B) {
        str := ascii()
        b.ResetTimer()
        for N := 0; N < b.N; N++ {
            is := isASCIIIndex(str)
            if !is {
                b.Log("notASCII")
            }
        }
    }
    
    func ascii() string {
        byt := make([]byte, unicode.MaxASCII+1)
        for i := range byt {
            byt[i] = byte(i)
        }
        return string(byt)
    }
    

    Output:

    $ go test ascii_test.go -bench=.
    BenchmarkRange-4    20000000    82.0 ns/op
    BenchmarkIndex-4    30000000    55.4 ns/op
    $
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用