How to convert string of []bytes to []bytes

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

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
}

huangapple
  • 本文由 发表于 2022年7月26日 22:14:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/73124976.html
匿名

发表评论

匿名网友

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

确定