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

huangapple go评论81阅读模式
英文:

How to convert a single character to a single byte?

问题

我正在尝试检查一个给定的字符是否存在于一个字节中:

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

"? "是字符串类型,所以我得到一个错误,因为readBuf[i]是一个字节。我该如何将"? "转换为字节,以便能够将其与readBuf[i]进行比较?

似乎[]byte("? ")[0]可以工作(将1个元素的字符串转换为1个元素的字节数组,然后提取第一个值),但我确定这不是正确的方法。

英文:

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

//readBuf: []byte
//n: int
for i:=0;i&lt;n;i++{
    if readBuf[i]==&quot;?&quot;{
    	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

得分: 4

rune literal &#39;?&#39; 是问号符的无类型整数值。

使用 bytes.ContainsRune

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

因为字符 ? 在 UTF-8 中被编码为单个字节,所以测试也可以写成:

for _, b := range readBuf[:n] {
    if b == '?' {   
        return true
    }
}
英文:

The rune literal &#39;?&#39; is the untyped integer value of the question mark rune.

Use bytes.ContainsRune:

if bytes.ContainsRune(readBuf[:n], &#39;?&#39;) {
   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 ==&#39;?&#39;{   
        return true
    }
}

huangapple
  • 本文由 发表于 2017年9月19日 13:37:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/46292602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定