(免责声明:我在Stack Overflow上的第一篇文章,也是Go语言和编码方面的新手。如果这个问题没有特殊要求,我深表歉意。因此,请告诉我如果需要可以做些什么)。

首先,说明我要实现的目标:

我正在尝试为footpatrol.com创建URL生成器。该程序将需要一些用户输入,例如产品名称和产品代码(SKU)的编号部分。然后,它将返回直接进入输入产品的URL。

我遇到的问题是'productName'变量(下面将提供代码)。产品名称将需要像“colour-brand-model-etc-etc”一样返回。但是,我的程序尚未执行此操作。我尝试使用功能Replace(),但是没有得到期望的结果。实际上,我没有得到任何结果,它只是返回我输入的第一个单词。

我的问题是,如何用'-'替换字符串中的空格。
我尝试过的特定代码:
newstr := strings.Replace(str, " ", "-", -1)。希望下面的代码更有意义。
此外,它仅返回我输入的第一个单词。例如,如果我输入“White Nike Air Force 1”,它将返回“White”。请参阅下面的代码,我将不胜感激。

无法使用的代码及其下面的工作代码:

package main

import (
    "fmt"
    "strings"

)

var skuNumber int
var productName []string

func main() {
    fmt.Println(`PLEASE NOTE: A Footpatrol product URL requires the "colour" followed by the name of product. Each word is seperated by a hyphen.`)

    fmt.Print("Enter the product name: ")
    str, err := fmt.Scanln(&productName)
    if err != nil {
        fmt.Println(err)
    }

    newstr := strings.Replace(string(str), " ", "-", -1)
    fmt.Scanln(&newstr)

    fmt.Print("Enter the SKU number: ")
    fmt.Scanln(&skuNumber)

    fmt.Print("https://www.footpatrol.com/product/", newstr, "/", skuNumber, "_footpatrolcom/\n")

}

代码有效,但需要输入准确的URL

package main

import (
    "fmt"
)

var skuNumber int
var productName string

func main() {
    fmt.Println(`PLEASE NOTE: A Footpatrol product URL requires the "colour" followed by the name of product. Each word is seperated by a hyphen.`)

    fmt.Print("Enter the product name: ")
    fmt.Scan(&productName)

    fmt.Print("Enter the SKU number: ")
    fmt.Scanln(&skuNumber)

    fmt.Print("https://www.footpatrol.com/product/", productName, "/", skuNumber, "_footpatrolcom/\n")

}

Output:
go run .\main.go
PLEASE NOTE: A Footpatrol product URL requires the "colour" followed by the name of product. Each word is seperated by a hyphen.
Enter the product name: red-nike-zoom-spiridon-cage-2
Enter the SKU number: 341503
https://www.footpatrol.com/product/red-nike-zoom-spiridon-cage-2/341503_footpatrolcom/

最佳答案

1.,您应该使用strings.ReplaceAll而不是strings.Replace
2.,在您的工作示例中,只需在fmt.Scan()之后添加以下行。

...
fmt.Scan(&productName)
productName = strings.ReplaceAll(productName, " ", "-")
...

在读取productName之后,这将替换所有出现的空格。

我希望这有帮助!

关于go - 用“-”替换字符串中的空格。使用fmt.Scan进行用户输入时。 ( golang ),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61899671/

10-12 07:25