strings.Trim is removing the letter "i" (golang)

huangapple go评论73阅读模式
英文:

strings.Trim is removing the letter "i" (golang)

问题

以下是要翻译的内容:

完整路径:views/admin/users.html
修剪集(views):/admin/users.html
修剪集(views/):admin/users.html

完整路径:views/index.html
修剪集(views):/index.html
修剪集(views/):ndex.html

这是我的代码:

err := filepath.Walk("./views", func(path string, info os.FileInfo, err error) error {
	if strings.Contains(path, ".html") {
		bytes, err := ioutil.ReadFile(path)
		if err != nil {
			panic(err)
		}
		fmt.Println("full path:", path)
		fmt.Println("trim set (views):", strings.Trim(path, "views"))
		fmt.Println("trim set (views/):", strings.Trim(path, "views/"))
	}
}

我是不是疯了?正斜杠与此有关吗?如果你知道,请解释一下发生了什么。

英文:
full path: views/admin/users.html
trim set (views): /admin/users.html
trim set (views/): admin/users.html

full path: views/index.html
trim set (views): /index.html
trim set (views/): ndex.html

Heres my code:

	err := filepath.Walk("./views", func(path string, info os.FileInfo, err error) error {
		if strings.Contains(path, ".html") {
			bytes, err := ioutil.ReadFile(path)
			if err != nil {
				panic(err)
			}
			fmt.Println("full path:", path)
			fmt.Println("trim set (views):", strings.Trim(path, "views"))
			fmt.Println("trim set (views/):", strings.Trim(path, "views/"))
        }
    }

Have I lost my mind? Does the forward slash have something to do with this? Please explain what's going on if you know.

答案1

得分: 6

string.Trim()的第二个参数是一个'cutset',即要从字符串中删除的一组符文,其中'i'是其中之一。

要返回除路径的最后一个元素之外的所有元素,请使用path.Dir()

英文:

The second parameter to strings.Trim() is a 'cutset', ie, a set of runes to remove from the strings, and 'i' is one of them.

To return all but the last element of path, use path.Dir().

答案2

得分: 1

你也可以使用strings.Replace函数:

fmt.Println("完整路径:", path)
fmt.Println("去除字符串(views):", strings.Replace(path, "views", "", -1))
fmt.Println("去除字符串(views/):", strings.Replace(path, "views/", "", -1))

结果:

完整路径: views/index.html
去除字符串(views): /index.html
去除字符串(views/): index.html
英文:

Also you can use strings.Replace:

fmt.Println("full path:", path)
fmt.Println("trim set (views):", strings.Replace(path, "views", "", -1))
fmt.Println("trim set (views/):", strings.Replace(path, "views/", "", -1))

Result:

full path: views/index.html
trim set (views): /index.html
trim set (views/): index.html

huangapple
  • 本文由 发表于 2017年2月15日 14:27:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/42242122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定