首页 > 解决方案 > 如何在 Go 中查找字符串的变量字段值?

问题描述

我有两个字符串:

str1: "与 %s 的连接已断开并抛出错误 %d"

str2:“与数据库的连接已关闭并引发错误401 ”

str2的帮助下str1,我想找出%s& %din的值是什么str2

标签: go

解决方案


您可以使用fmt.Sscanf,它是字符串和 fromat 版本fmt.Scan

package main

import (
    "fmt"
)

func main() {
    str1 := "Connection to %s is down and error %d is thrown"
    str2 := "Connection to DataBase is down and error 401 is thrown"
    var s string
    var d int
    _, err := fmt.Sscanf(str2, str1, &s, &d)
    if err != nil {
        panic(err)
    }
    fmt.Println(s, d)
}

操场: https: //play.golang.org/p/5g5UcrHsunM

注意:您似乎正在解析错误。如果错误来自 Go,很可能它提供了错误内部的数据,因此您无需手动解析它。如果您可以控制错误,最好将数据存储在里面。


推荐阅读