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

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

How to convert string with index number to target slice item

问题

我有这个字符串:

  1. "books[1]"

我有这个切片:

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

如何将这个字符串转换为能够定位到books索引1的形式,就像下面这样:

  1. fmt.Println("书名:", books[1]) // 书名:bededaw
英文:

I have this string:

  1. "books[1]"

And I have this slice:

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

How to convert this string: "books[1]" to be able to target books index 1 like the following:

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

答案1

得分: 2

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

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. func main() {
  7. books := map[int]string{
  8. 0: "wadidaw",
  9. 1: "bededaw",
  10. 2: "celepaw",
  11. }
  12. target := "books[1]"
  13. value, err := getValueByString(target, books)
  14. if err != nil {
  15. fmt.Println("Error:", err)
  16. } else {
  17. fmt.Println("Book title:", value)
  18. }
  19. }
  20. func getValueByString(target string, data map[int]string) (interface{}, error) {
  21. parts := splitTarget(target)
  22. if len(parts) != 2 {
  23. return nil, fmt.Errorf("invalid target format: %s", target)
  24. }
  25. // 获取变量名和索引
  26. varName := parts[0]
  27. index, err := strconv.Atoi(parts[1])
  28. if err != nil {
  29. return nil, fmt.Errorf("invalid index: %s", parts[1])
  30. }
  31. // 检查变量是否存在
  32. value, ok := data[index]
  33. if !ok {
  34. return nil, fmt.Errorf("variable not found: %s", varName)
  35. }
  36. return value, nil
  37. }
  38. func splitTarget(target string) []string {
  39. parts := make([]string, 2)
  40. // 找到开括号的索引
  41. braceIndex := -1
  42. for i, char := range target {
  43. if char == '[' {
  44. braceIndex = i
  45. break
  46. }
  47. }
  48. // 提取变量名和索引
  49. if braceIndex != -1 {
  50. parts[0] = target[:braceIndex]
  51. parts[1] = target[braceIndex+1 : len(target)-1]
  52. }
  53. return parts
  54. }

请随意使用 Go Playground 进行测试。

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

英文:

You'll need to parse string as code.

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. func main() {
  7. books := map[int]string{
  8. 0: "wadidaw",
  9. 1: "bededaw",
  10. 2: "celepaw",
  11. }
  12. target := "books[1]"
  13. value, err := getValueByString(target, books)
  14. if err != nil {
  15. fmt.Println("Error:", err)
  16. } else {
  17. fmt.Println("Book title:", value)
  18. }
  19. }
  20. func getValueByString(target string, data map[int]string) (interface{}, error) {
  21. parts := splitTarget(target)
  22. if len(parts) != 2 {
  23. return nil, fmt.Errorf("invalid target format: %s", target)
  24. }
  25. // Get the variable name and index
  26. varName := parts[0]
  27. index, err := strconv.Atoi(parts[1])
  28. if err != nil {
  29. return nil, fmt.Errorf("invalid index: %s", parts[1])
  30. }
  31. // Check if the variable exists
  32. value, ok := data[index]
  33. if !ok {
  34. return nil, fmt.Errorf("variable not found: %s", varName)
  35. }
  36. return value, nil
  37. }
  38. func splitTarget(target string) []string {
  39. parts := make([]string, 2)
  40. // Find the index of the opening bracket
  41. braceIndex := -1
  42. for i, char := range target {
  43. if char == '[' {
  44. braceIndex = i
  45. break
  46. }
  47. }
  48. // Extract the variable name and index
  49. if braceIndex != -1 {
  50. parts[0] = target[:braceIndex]
  51. parts[1] = target[braceIndex+1 : len(target)-1]
  52. }
  53. return parts
  54. }

Please feel free to use the Go playground

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

答案2

得分: 0

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

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. )
  7. func main() {
  8. books := []string{
  9. "wadidaw",
  10. "bededaw",
  11. "celepaw",
  12. }
  13. str := "books[1]"
  14. index, sliceName, err := getIndex(str)
  15. if err != nil {
  16. panic(err)
  17. }
  18. // 检查索引是否有效,它应该大于0且小于(切片长度-1)
  19. if index < 0 || index > len(books)-1 {
  20. panic("无效的索引")
  21. }
  22. fmt.Println("切片名称:", sliceName)
  23. fmt.Println("值:", books[index])
  24. }
  25. func getIndex(str string) (int, string, error) {
  26. // 在 [ 处拆分字符串
  27. parts := strings.Split(str, "[")
  28. if len(parts) != 2 {
  29. return 0, "", fmt.Errorf("无法解析 %v,语法无效", str)
  30. }
  31. name := parts[0]
  32. index := strings.TrimSuffix(parts[1], "]")
  33. // 将索引转换为整数
  34. indexInt, err := strconv.Atoi(index)
  35. if err != nil {
  36. return 0, "", fmt.Errorf("无法将 '%s' 解析为整数", index)
  37. }
  38. return indexInt, name, nil
  39. }
英文:

Here is a very simple approach to parse the string and getting the index value.

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;strconv&quot;
  5. &quot;strings&quot;
  6. )
  7. func main() {
  8. books := []string{
  9. &quot;wadidaw&quot;,
  10. &quot;bededaw&quot;,
  11. &quot;celepaw&quot;,
  12. }
  13. str := &quot;books[1]&quot;
  14. index, sliceName, err := getIndex(str)
  15. if err != nil {
  16. panic(err)
  17. }
  18. // Check the index is valid as it will be greater than 0 and less than (slice length - 1)
  19. if index &lt; 0 || index &gt; len(books)-1 {
  20. panic(&quot;invalid index&quot;)
  21. }
  22. fmt.Println(&quot;Slice name : &quot;, sliceName)
  23. fmt.Println(&quot;Value : &quot;, books[index])
  24. }
  25. func getIndex(str string) (int, string, error) {
  26. // split the string at [
  27. parts := strings.Split(str, &quot;[&quot;)
  28. if len(parts) != 2 {
  29. return 0, &quot;&quot;, fmt.Errorf(&quot;unable to parse %v, invalid syntax&quot;, str)
  30. }
  31. name := parts[0]
  32. index := strings.TrimSuffix(parts[1], &quot;]&quot;)
  33. // convert the index into int
  34. indexInt, err := strconv.Atoi(index)
  35. if err != nil {
  36. return 0, &quot;&quot;, fmt.Errorf(&quot;unable to parse &#39;%s&#39; into int&quot;, index)
  37. }
  38. return indexInt, name, nil
  39. }

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:

确定