duanmao1919 2016-04-21 06: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-21 07: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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!