duanchuopi2298
duanchuopi2298
2017-09-19 05:37
浏览 60
已采纳

如何将单个字符转换为单个字节?

I am trying to check if a given character is present in a byte:

//readBuf: []byte
//n: int
for i:=0;i<n;i++{
    if readBuf[i]=="?"{
        return true
    }
}

"?" is of type string, so I am getting an error, since readBuf[i] is a byte. How can I convert "?" to a byte to be able to compare it to readBuf[i]?

It seems that []byte("?")[0] is working (convert the 1-element string to 1-element byte array, the extract the first value), but I am sure this is not the correct way of doing it.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongmo9996
    dongmo9996 2017-09-19 05:51
    已采纳

    The rune literal '?' is the untyped integer value of the question mark rune.

    Use bytes.ContainsRune:

    if bytes.ContainsRune(readBuf[:n], '?') {
       return true
    }
    

    Because the character ? is encoded as a single byte in UTF-8, the test can also be written as:

    for _, b := range readBuf[:n] {
        if b =='?'{   
            return true
        }
    }
    
    点赞 评论

相关推荐