英文:
How to convert string with index number to target slice item
问题
我有这个字符串:
"books[1]"
我有这个切片:
books := []string{"wadidaw", "bededaw", "celepaw"}
如何将这个字符串转换为能够定位到books索引1的形式,就像下面这样:
fmt.Println("书名:", books[1]) // 书名:bededaw
英文:
I have this string:
"books[1]"
And I have this slice:
books := []string{"wadidaw", "bededaw", "celepaw"}
How to convert this string: "books[1]"
to be able to target books index 1 like the following:
fmt.Println("Book title: ", books[1]) // Book title: bededaw
答案1
得分: 2
你需要将字符串解析为代码。
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)
}
// 获取变量名和索引
varName := parts[0]
index, err := strconv.Atoi(parts[1])
if err != nil {
return nil, fmt.Errorf("invalid index: %s", parts[1])
}
// 检查变量是否存在
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)
// 找到开括号的索引
braceIndex := -1
for i, char := range target {
if char == '[' {
braceIndex = i
break
}
}
// 提取变量名和索引
if braceIndex != -1 {
parts[0] = target[:braceIndex]
parts[1] = target[braceIndex+1 : len(target)-1]
}
return parts
}
请随意使用 Go Playground 进行测试。
https://go.dev/play/p/-q2JUn-N4Sg
英文:
You'll need to parse string as code.
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
}
Please feel free to use the Go playground
答案2
得分: 0
这是一种非常简单的方法来解析字符串并获取索引值。
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)
}
// 检查索引是否有效,它应该大于0且小于(切片长度-1)
if index < 0 || index > len(books)-1 {
panic("无效的索引")
}
fmt.Println("切片名称:", sliceName)
fmt.Println("值:", books[index])
}
func getIndex(str string) (int, string, error) {
// 在 [ 处拆分字符串
parts := strings.Split(str, "[")
if len(parts) != 2 {
return 0, "", fmt.Errorf("无法解析 %v,语法无效", str)
}
name := parts[0]
index := strings.TrimSuffix(parts[1], "]")
// 将索引转换为整数
indexInt, err := strconv.Atoi(index)
if err != nil {
return 0, "", fmt.Errorf("无法将 '%s' 解析为整数", index)
}
return indexInt, name, nil
}
英文:
Here is a very simple approach to parse the string and getting the index value.
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论