Go语言 如何将带索引号的字符串转换为目标切片项

hyrbngr7  于 2023-06-27  发布在  Go
关注(0)|答案(2)|浏览(127)

我有这个字符串:

"books[1]"

我有这样的切片:

books := []string{"wadidaw", "bededaw", "celepaw"}

如何转换此字符串:"books[1]"可以像下面这样定位books index 1:

fmt.Println("Book title: ", books[1]) // Book title: bededaw
bgtovc5b

bgtovc5b1#

您需要将字符串解析为代码。

package main

import (
    "fmt"
    "strconv"
)

func main() {
    books := map[int]string{
        0: "wadidaw",
        1: "bededaw",
        2: "celepaw",
    }

    target := "books[1]"
    value, err := getValueByString(target, books)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Book title:", value)
    }
}

func getValueByString(target string, data map[int]string) (interface{}, error) {
    parts := splitTarget(target)
    if len(parts) != 2 {
        return nil, fmt.Errorf("invalid target format: %s", target)
    }

    // Get the variable name and index
    varName := parts[0]
    index, err := strconv.Atoi(parts[1])
    if err != nil {
        return nil, fmt.Errorf("invalid index: %s", parts[1])
    }

    // Check if the variable exists
    value, ok := data[index]
    if !ok {
        return nil, fmt.Errorf("variable not found: %s", varName)
    }

    return value, nil
}

func splitTarget(target string) []string {
    parts := make([]string, 2)

    // Find the index of the opening bracket
    braceIndex := -1
    for i, char := range target {
        if char == '[' {
            braceIndex = i
            break
        }
    }

    // Extract the variable name and index
    if braceIndex != -1 {
        parts[0] = target[:braceIndex]
        parts[1] = target[braceIndex+1 : len(target)-1]
    }

    return parts
}

请随意使用围棋场
https://go.dev/play/p/-q2JUn-N4Sg

n9vozmp4

n9vozmp42#

这里有一个非常简单的方法来解析字符串并获取索引值。

package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    books := []string{
        "wadidaw",
        "bededaw",
        "celepaw",
    }
    str := "books[1]"

    index, sliceName, err := getIndex(str)
    if err != nil {
        panic(err)
    }

    // Check the index is valid as it will be greater than 0 and less than (slice length - 1)
    if index < 0 || index > len(books)-1 {
        panic("invalid index")
    }

    fmt.Println("Slice name : ", sliceName)
    fmt.Println("Value : ", books[index])
}

func getIndex(str string) (int, string, error) {
    // split the string at [
    parts := strings.Split(str, "[")
    if len(parts) != 2 {
        return 0, "", fmt.Errorf("unable to parse %v, invalid syntax", str)
    }

    name := parts[0]
    index := strings.TrimSuffix(parts[1], "]")

    // convert the index into int
    indexInt, err := strconv.Atoi(index)
    if err != nil {
        return 0, "", fmt.Errorf("unable to parse '%s' into int", index)
    }
    return indexInt, name, nil
}

相关问题