duanmao1919 2016-04-20 22:58
浏览 240
已采纳

如何使用UTF-8字符串检查golang中的字符值?

I'm attempting to check if the first character in a string matches the following, note the UTF-8 quote characters:

c := t.Content[0]
if c != '.' && c != ',' && c != '?' && c != '“' && c != '”'{

This code does not work due to the special characters in the last two checks.

What is the correct way to do this?

  • 写回答

2条回答 默认 最新

  • dongnai5905 2016-04-20 23:07
    关注

    Indexing a string indexes its bytes (in UTF-8 encoding - this is how Go stores strings in memory), but you want to test the first character.

    So you should get the first rune and not the first byte. For efficiency you may use utf8.DecodeRuneInString() which only decodes the first rune. If you need all the runes of the string, you may use type conversion like all := []rune("I'm a string").

    See this example:

    for _, s := range []string{"asdf", ".asdf", "”asdf"} {
        c, _ := utf8.DecodeRuneInString(s)
        if c != '.' && c != ',' && c != '?' && c != '“' && c != '”' {
            fmt.Println("Ok:", s)
        } else {
            fmt.Println("Not ok:", s)
        }
    }
    

    Output (try it on the Go Playground):

    Ok: asdf
    Not ok: .asdf
    Not ok: ”asdf
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部