drsh30452 2016-01-27 16:45
浏览 164
已采纳

如何忽略fmt.Sprintf的其他字段

I have a Golang program that reads a string parameter from command line and passes it to the fmt.Sprintf function. Let's say tmp_str is the target string from command line.

package main

import "fmt"

func main() {
    tmp_str := "hello %s"
    str := fmt.Sprintf(tmp_str, "world")
    fmt.Println(str)
}

In some cases, the program will pass a completed string like "Hello Friends", instead of a string template.. The program would panic and return:

Hello Friends%!(EXTRA string=world)

So, how to ignore the extra fields for fmt.Sprintf?

  • 写回答

5条回答 默认 最新

  • dongpaipu8394 2016-01-27 17:46
    关注

    Yes you can do it, by slicing the arguments you pass to the variadic Sprintf function:

    func TruncatingSprintf(str string, args ...interface{}) (string, error) {
        n := strings.Count(str, "%s")
        if n > len(args) {
            return "", errors.New("Unexpected string:" + str)
        }
        return fmt.Sprintf(str, args[:n]...), nil
    }
    
    func main() {
        tmp_str := "hello %s %s %s"         // don't hesitate to add many %s here
        str, err := TruncatingSprintf(tmp_str, "world") // or many arguments here
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(str)
    }
    

    Demonstration 1

    Demonstration 2 (a different version outputting even when there's more %s than arguments)

    But you don't usually use dynamic formatted strings, this isn't secure and if you want to accept any string, you should also adapt this code to no choke on %%s. If you venture this far, then you should probably have a look at templates (which would let you use named strings, and thus the missing one wouldn't have to be the last one).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格