登录
首页 >  Golang >  Go问答

将字符串中的空格替换为“-”。同时使用 fmt.Scan 进行用户输入。 (戈兰)

来源:stackoverflow

时间:2024-04-25 23:06:37 422浏览 收藏

golang学习网今天将给大家带来《将字符串中的空格替换为“-”。同时使用 fmt.Scan 进行用户输入。 (戈兰)》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

(免责声明:我在 stack overflow 上发表的第一篇文章,对 go 和一般编码也非常陌生。如果这个问题缺乏具体要求,我深表歉意。所以,如果需要,请告诉我可以更改哪些内容)。

首先,描述我想要实现的目标:

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

我遇到的问题是“productname”变量(下面将提供代码)。需要返回产品名称,如“颜色-品牌-型号等”。但是,我的程序还没有这样做。我尝试过使用 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, " ", "-")
...

这将替换您读取产品名称后出现的所有空格。

希望这会有所帮助!

今天关于《将字符串中的空格替换为“-”。同时使用 fmt.Scan 进行用户输入。 (戈兰)》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>