英文:
How to convert string of []bytes to []bytes
问题
main.go
package main
import "fmt"
func main() {
rawString := "Hello World"
myStringBytes := fmt.Sprint([]byte(rawString))
myResultString := string([]byte(myStringBytes))
fmt.Println(myResultString)
fmt.Println(rawString)
}
输出
[72 101 108 108 111 32 87 111 114 108 100]
Hello World
为什么 myResultString
仍然是字节形式?
如何将 []bytes 的字符串转换为 []bytes?
我希望 myResultString
== rawString
英文:
main.go
package main
import "fmt"
func main() {
rawString := "Hello World"
myStringBytes := fmt.Sprint([]byte(rawString))
myResultString := string([]byte(myStringBytes))
fmt.Println(myResultString)
fmt.Println(rawString)
}
Output
[72 101 108 108 111 32 87 111 114 108 100]
Hello World
Why myResultString
still in bytes form?
How to convert the string of []bytes to []bytes?
I want myResultString
== rawString
答案1
得分: 1
刚刚使用这个函数解决了这个问题。
顺便说一下,我使用这种方法从HTML请求中解析分号查询参数(:
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
rawString := "Hello World"
myStringBytes := fmt.Sprint([]byte(rawString))
myResultString, _ := string(StringBytesParseString(myStringBytes))
fmt.Println(myResultString)
fmt.Println(rawString)
}
func StringBytesParseString(byteString string) (string, error) {
byteString = strings.TrimSuffix(byteString, "]")
byteString = strings.TrimLeft(byteString, "[")
sByteString := strings.Split(byteString, " ")
var res []byte
for _, s := range sByteString {
i, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return "", err
}
res = append(res, byte(i))
}
return string(res), nil
}
英文:
Just used this function to resolve this problem.
Fyi, I used this method to parse semi colon query param from HTML request (:
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
rawString := "Hello World"
myStringBytes := fmt.Sprint([]byte(rawString))
myResultString, _ := string(StringBytesParseString(myStringBytes))
fmt.Println(myResultString)
fmt.Println(rawString)
}
func StringBytesParseString(byteString string) (string, error) {
byteString = strings.TrimSuffix(byteString, "]")
byteString = strings.TrimLeft(byteString, "[")
sByteString := strings.Split(byteString, " ")
var res []byte
for _, s := range sByteString {
i, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return "", err
}
res = append(res, byte(i))
}
return string(res), nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论