英文:
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<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
得分: 4
rune literal '?'
是问号符的无类型整数值。
if bytes.ContainsRune(readBuf[:n], '?') {
return true
}
因为字符 ?
在 UTF-8 中被编码为单个字节,所以测试也可以写成:
for _, b := range readBuf[:n] {
if b == '?' {
return true
}
}
英文:
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论