【问题标题】:How to check value of character in golang with UTF-8 strings?如何使用 UTF-8 字符串检查 golang 中字符的值?
【发布时间】:2016-08-14 04:53:34
【问题描述】:

我正在尝试检查字符串中的第一个字符是否与以下字符匹配,请注意 UTF-8 引号字符:

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

由于最后两次检查中的特殊字符,此代码不起作用。

这样做的正确方法是什么?

【问题讨论】:

  • t.Contentstring 类型的吗?
  • Content[0] 访问第一个 字节 而不是第一个字符/代码点/符文。在 UTF-8 中,符文可能由多个字节表示。将您的字符串转换为符文切片 ([]rune(t.Content)) 或使用 unicode/utf8/DecodeRuneInString 和相关函数。
  • 哇,“符文切片”。我不知道那个,那也可以解决它。谢谢!

标签: string go utf-8


【解决方案1】:

索引string 索引其字节(以 UTF-8 编码 - 这是 Go 在内存中存储字符串的方式),但您想测试第一个字符。

所以你应该得到第一个rune,而不是第一个byte。为了提高效率,您可以使用utf8.DecodeRuneInString(),它只解码第一个rune。如果你需要string的所有符文,你可以使用all := []rune("I'm a string")这样的类型转换。

看这个例子:

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)
    }
}

输出(在Go Playground上试试):

Ok: asdf
Not ok: .asdf
Not ok: ”asdf

【讨论】:

    【解决方案2】:

    补充@icza 的最佳答案:值得注意的是,虽然字符串的索引以字节为单位,但字符串的range 以符文为单位。所以以下也有效:

    for _, s := range []string{"asdf", ".asdf", "”asdf"} {
        for _, c := range s {
            if c != '.' && c != ',' && c != '?' && c != '“' && c != '”' {
                fmt.Println("Ok:", s)
            } else {
                fmt.Println("Not ok:", s)
            }
            break // we break after the first character regardless
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-03
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 2011-01-23
      • 1970-01-01
      • 2017-09-16
      相关资源
      最近更新 更多