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

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

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

https://go.dev/play/p/-q2JUn-N4Sg

答案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 (
&quot;fmt&quot;
&quot;strconv&quot;
&quot;strings&quot;
)
func main() {
books := []string{
&quot;wadidaw&quot;,
&quot;bededaw&quot;,
&quot;celepaw&quot;,
}
str := &quot;books[1]&quot;
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 &lt; 0 || index &gt; len(books)-1 {
panic(&quot;invalid index&quot;)
}
fmt.Println(&quot;Slice name : &quot;, sliceName)
fmt.Println(&quot;Value : &quot;, books[index])
}
func getIndex(str string) (int, string, error) {
// split the string at [
parts := strings.Split(str, &quot;[&quot;)
if len(parts) != 2 {
return 0, &quot;&quot;, fmt.Errorf(&quot;unable to parse %v, invalid syntax&quot;, str)
}
name := parts[0]
index := strings.TrimSuffix(parts[1], &quot;]&quot;)
// convert the index into int
indexInt, err := strconv.Atoi(index)
if err != nil {
return 0, &quot;&quot;, fmt.Errorf(&quot;unable to parse &#39;%s&#39; into int&quot;, index)
}
return indexInt, name, nil
}

huangapple
  • 本文由 发表于 2023年6月21日 11:49:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76519824.html
匿名

发表评论

匿名网友

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

确定