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