duanche4578 2015-12-11 02:14
浏览 255
已采纳

Strings.Replacer:如何一次替换所有子字符串?

I am trying to replace multiple different characters from a string using Replacer but having issues replacing one string. Output has two underscores instead of one, and if I try replacing using other Replacer, then it cannot replace it entirely.

Try the code on the Go Playground:

package main

import (
    "fmt"
    "strings"
    )

//Expecting output to be emp_my_stats

func main() {
    var input string = "/v1.0/emp/emp_1/my_stats"

    replacer := strings.NewReplacer("/v1.0/", "", "/", "_", "emp_1", "")
//  replacer := strings.NewReplacer("/v1.0/", "", "/", "_", "/emp_1", "")

    output := replacer.Replace(input)
    fmt.Printf("output %v", output) 
}

I can use multiple Replacer etc. but would really like to do it in one pass / or one statement.

Any suggestions how so do it cleanly? My goal is to be efficient (this will be done frequently, so important although these strings are short) and also to not use multiple Replacers.

  • 写回答

2条回答 默认 最新

  • duanpuluan0480 2015-12-11 06:48
    关注

    You haven't specified any other possible inputs, but it looks that from this:

    input := "/v1.0/emp/emp_1/my_stats"
    

    You need the "emp" and "my_stats" parts connected with an underscore '_'. And judging by your attempt for the replacer, "/v1.0/" and "/emp_1/" parts are static, so you can simply do this with one replacer:

    replacer := strings.NewReplacer("/v1.0/", "", "/emp_1/", "_")
    

    Complete example:

    input := "/v1.0/emp/emp_1/my_stats"
    
    replacer := strings.NewReplacer("/v1.0/", "", "/emp_1/", "_")
    
    output := replacer.Replace(input)
    fmt.Println("Output:", output)
    

    Output (try it on the Go Playground):

    Output: emp_my_stats
    

    Notes:

    You mentioned you have to do this frequently and you want this to be efficient. So make sure you only create one Replacer, and reuse it whenever you need to do the replacing (e.g. you can store it in a global variable initialized once). Judging from your input, it looks like it is the path of some URL, and most likely you want to do this is HTTP handlers, which may run concurrently on multiple goroutines. It is safe to use a Replacer from multiple goroutines, quoting from the doc of Replacer:

    It is safe for concurrent use by multiple goroutines.

    Notes #2:

    If the "/v1.0/" and "/emp_1/" parts in the input are not static, you can't really solve your problem with a Replacer. In this case you may use regexp or as a more efficient solution, splitting the string by '/' and joining the relevant parts with '_'.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度