Go是否有任何方法或建议如何检查字符串是否仅包含ASCII字符?正确的做法是什么?

根据我的研究,解决方案之一是检查是否有大于127的字符。

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

    return true
}

最佳答案

在Go中,我们关心性能,因此,我们将对您的代码进行基准测试:

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

BenchmarkRange-4    20000000    82.0 ns/op

更快(更好,更惯用)的版本,可避免不必要的 rune 转换:
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)
}

输出:
$ go test ascii_test.go -bench=.
BenchmarkRange-4    20000000    82.0 ns/op
BenchmarkIndex-4    30000000    55.4 ns/op
$

关于go - 检查字符串仅包含ASCII字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53069040/

10-12 17:14
查看更多